fs.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. /**
  9. * @typedef {object} ReadJsonOptions
  10. * @property {boolean=} stripComments Whether to strip JSONC comments
  11. */
  12. /**
  13. * Read and parse JSON file (supports JSONC with comments)
  14. * @template T
  15. * @param {FileSystem} fileSystem the file system
  16. * @param {string} jsonFilePath absolute path to JSON file
  17. * @param {ReadJsonOptions} options Options
  18. * @returns {Promise<T>} parsed JSON content
  19. */
  20. async function readJson(fileSystem, jsonFilePath, options = {}) {
  21. const { stripComments = false } = options;
  22. const { readJson } = fileSystem;
  23. if (readJson && !stripComments) {
  24. return new Promise((resolve, reject) => {
  25. readJson(jsonFilePath, (err, content) => {
  26. if (err) return reject(err);
  27. resolve(/** @type {T} */ (content));
  28. });
  29. });
  30. }
  31. const buf = await new Promise((resolve, reject) => {
  32. fileSystem.readFile(jsonFilePath, (err, data) => {
  33. if (err) return reject(err);
  34. resolve(data);
  35. });
  36. });
  37. const jsonText = /** @type {string} */ (buf.toString());
  38. // Strip comments to support JSONC (e.g., tsconfig.json with comments)
  39. const jsonWithoutComments = stripComments
  40. ? stripJsonComments(jsonText, { trailingCommas: true, whitespace: true })
  41. : jsonText;
  42. return JSON.parse(jsonWithoutComments);
  43. }
  44. module.exports.readJson = readJson;