Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

suggestion #23

Closed
jimmywarting opened this issue Aug 30, 2021 · 6 comments
Closed

suggestion #23

jimmywarting opened this issue Aug 30, 2021 · 6 comments

Comments

@jimmywarting
Copy link

Would be nice if this had 0 dependencies:

import {readFileSync} from 'node:fs';
import {readFile} from 'node:fs/promises';

const parse = (uint8, options = {}) => {
  // unlike buf.toString('utf8') or or readFile(path, 'utf8'), TextDecoder will remove BOM
  let data = new TextDecoder().decode(uint8);

  if (typeof options.beforeParse === 'function') {
    data = options.beforeParse(data);
  }

  return JSON.parse(data, options.reviver);
};

export const loadJsonFile = (filePath, options) =>
  readFile(filePath).then(data => parse(data, options));

export const loadJsonFileSync = (filePath, options) =>
  parse(readFileSync(filePath), options);
@sindresorhus
Copy link
Owner

sindresorhus commented Aug 30, 2021

Yeah, we could probably reduce the dependencies. graceful-fs was useful in the past, but it's too hacky and less useful these days. parse-json would probably stay though as it improves JSON errors. I'll work on ESMifying this package later today.

Sidenote: I really wish Node.js had a fs.readJson built-in method with good JSON errors, since it's such a common use-case. Maybe you should open an issue about that on the Node.js issue tracker. This kinda basic stuff should really be built-in.

@jimmywarting
Copy link
Author

that could maybe change with the (dynamic) "import json" proposal

@jimmywarting
Copy link
Author

one new additions that arrived into node was stream-consumers.
among it was json(iterable).then(console.log)

the idea came from fetch's response.json() so it should strip BOM also i guess
so you could do: await json(fs.createReadStream(path))

but this is only async, there is no sync alternative, and gives even worse error

@sindresorhus
Copy link
Owner

that could maybe change with the (dynamic) "import json" proposal

Importing JSON and reading JSON are different. Importing has overhead and also caches. Reading directly from disk will always be faster.

@sindresorhus
Copy link
Owner

I ended up dropping parse-json. Not worth the bloat.

https://github.com/sindresorhus/load-json-file/releases/tag/v7.0.0

@jimmywarting
Copy link
Author

Thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants