fs.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Natsu @xiaoxiaojx
  4. */
  5. "use strict";
  6. const stripJsonComments = require("./strip-json-comments");
  7. /** @typedef {import("../Resolver").FileSystem} FileSystem */
  8. /** @typedef {import("../Resolver").JsonObject} JsonObject */
  9. /**
  10. * @typedef {object} ReadJsonOptions
  11. * @property {boolean=} stripComments Whether to strip JSONC comments
  12. */
  13. /** @type {WeakMap<Buffer, JsonObject>} */
  14. const _stripCommentsCache = new WeakMap();
  15. /**
  16. * Read and parse JSON file (supports JSONC with comments).
  17. * Callback-based so a synchronous `fileSystem` stays synchronous all the
  18. * way through — Promise wrapping would defer resolution by a Promise tick
  19. * and break `resolveSync` when `tsconfig` is used together with
  20. * `useSyncFileSystemCalls: true`.
  21. * @param {FileSystem} fileSystem the file system
  22. * @param {string} jsonFilePath absolute path to JSON file
  23. * @param {ReadJsonOptions} options Options
  24. * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback
  25. * @returns {void}
  26. */
  27. function readJson(fileSystem, jsonFilePath, options, callback) {
  28. const { stripComments = false } = options;
  29. const { readJson: fsReadJson } = fileSystem;
  30. if (fsReadJson && !stripComments) {
  31. fsReadJson(jsonFilePath, (err, content) => {
  32. if (err) return callback(err);
  33. callback(null, /** @type {JsonObject} */ (content));
  34. });
  35. return;
  36. }
  37. fileSystem.readFile(jsonFilePath, (err, data) => {
  38. if (err) return callback(err);
  39. const buf = /** @type {Buffer} */ (data);
  40. if (stripComments) {
  41. const cached = _stripCommentsCache.get(buf);
  42. if (cached !== undefined) return callback(null, cached);
  43. }
  44. let result;
  45. try {
  46. const jsonText = buf.toString();
  47. const jsonWithoutComments = stripComments
  48. ? stripJsonComments(jsonText, {
  49. trailingCommas: true,
  50. whitespace: true,
  51. })
  52. : jsonText;
  53. result = JSON.parse(jsonWithoutComments);
  54. } catch (parseErr) {
  55. return callback(/** @type {Error} */ (parseErr));
  56. }
  57. if (stripComments) {
  58. _stripCommentsCache.set(buf, result);
  59. }
  60. callback(null, result);
  61. });
  62. }
  63. module.exports.readJson = readJson;