fs.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Natsu @xiaoxiaojx
  4. */
  5. "use strict";
  6. const memoize = require("./memoize");
  7. const stripJsonComments = require("./strip-json-comments");
  8. /** @typedef {import("../Resolver").FileSystem} FileSystem */
  9. /** @typedef {import("../Resolver").JsonObject} JsonObject */
  10. /**
  11. * @typedef {object} ReadJsonOptions
  12. * @property {boolean=} stripComments Whether to strip JSONC comments
  13. */
  14. /** @type {WeakMap<Buffer | Uint8Array, JsonObject>} */
  15. const _stripCommentsCache = new WeakMap();
  16. // Only constructed for non-Buffer input: on Node the `Buffer.isBuffer` branch
  17. // in `decodeText` handles decoding, so the global `TextDecoder` (Node 11+,
  18. // always present in browsers/Deno/Bun) is only reached off the Buffer path.
  19. // `ignoreBOM: true` keeps a leading BOM in the output, matching
  20. // `Buffer.toString("utf8")` so both decode paths behave identically.
  21. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  22. const getDecoder = memoize(() => new TextDecoder("utf-8", { ignoreBOM: true }));
  23. /**
  24. * Decode a file's raw contents to text without assuming a Node runtime. A
  25. * `Buffer` (Node) uses its fast native `toString`; any other binary input
  26. * (`Uint8Array` from a browser/Deno/Bun file system) goes through
  27. * `TextDecoder`, and strings are returned as-is.
  28. * @param {string | Buffer | Uint8Array} data raw file contents
  29. * @returns {string} decoded text
  30. */
  31. const decodeText = (data) => {
  32. if (typeof data === "string") return data;
  33. if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
  34. return data.toString("utf8");
  35. }
  36. return getDecoder().decode(data);
  37. };
  38. /**
  39. * Read and parse JSON file (supports JSONC with comments).
  40. * Callback-based so a synchronous `fileSystem` stays synchronous all the
  41. * way through — Promise wrapping would defer resolution by a Promise tick
  42. * and break `resolveSync` when `tsconfig` is used together with
  43. * `useSyncFileSystemCalls: true`.
  44. * @param {FileSystem} fileSystem the file system
  45. * @param {string} jsonFilePath absolute path to JSON file
  46. * @param {ReadJsonOptions} options Options
  47. * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback
  48. * @returns {void}
  49. */
  50. function readJson(fileSystem, jsonFilePath, options, callback) {
  51. const { stripComments = false } = options;
  52. const { readJson: fsReadJson } = fileSystem;
  53. if (fsReadJson && !stripComments) {
  54. fsReadJson(jsonFilePath, (err, content) => {
  55. if (err) return callback(err);
  56. callback(null, /** @type {JsonObject} */ (content));
  57. });
  58. return;
  59. }
  60. fileSystem.readFile(jsonFilePath, (err, data) => {
  61. if (err) return callback(err);
  62. const buf = /** @type {Buffer | Uint8Array | string} */ (data);
  63. // The strip-comments cache is keyed by the file-contents object; a file
  64. // system may hand back a plain string, which cannot be a WeakMap key, so
  65. // only cache when the contents are an object.
  66. const cacheable = stripComments && typeof buf === "object";
  67. if (cacheable) {
  68. const cached = _stripCommentsCache.get(buf);
  69. if (cached !== undefined) return callback(null, cached);
  70. }
  71. let result;
  72. try {
  73. const jsonText = decodeText(buf);
  74. const jsonWithoutComments = stripComments
  75. ? stripJsonComments(jsonText, {
  76. trailingCommas: true,
  77. whitespace: true,
  78. })
  79. : jsonText;
  80. result = JSON.parse(jsonWithoutComments);
  81. } catch (parseErr) {
  82. return callback(/** @type {Error} */ (parseErr));
  83. }
  84. if (cacheable) {
  85. _stripCommentsCache.set(buf, result);
  86. }
  87. callback(null, result);
  88. });
  89. }
  90. module.exports.decodeText = decodeText;
  91. module.exports.readJson = readJson;