Blame view

天文台pc/tianwentai-ui/node_modules/enhanced-resolve/lib/util/fs.js 1.47 KB
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  /*
  	MIT License http://www.opensource.org/licenses/mit-license.php
  	Author Natsu @xiaoxiaojx
  */
  
  "use strict";
  
  const stripJsonComments = require("./strip-json-comments");
  
  /** @typedef {import("../Resolver").FileSystem} FileSystem */
  
  /**
   * @typedef {object} ReadJsonOptions
   * @property {boolean=} stripComments Whether to strip JSONC comments
   */
  
  /**
   * Read and parse JSON file (supports JSONC with comments)
   * @template T
   * @param {FileSystem} fileSystem the file system
   * @param {string} jsonFilePath absolute path to JSON file
   * @param {ReadJsonOptions} options Options
   * @returns {Promise<T>} parsed JSON content
   */
  async function readJson(fileSystem, jsonFilePath, options = {}) {
  	const { stripComments = false } = options;
  	const { readJson } = fileSystem;
  	if (readJson && !stripComments) {
  		return new Promise((resolve, reject) => {
  			readJson(jsonFilePath, (err, content) => {
  				if (err) return reject(err);
  				resolve(/** @type {T} */ (content));
  			});
  		});
  	}
  
  	const buf = await new Promise((resolve, reject) => {
  		fileSystem.readFile(jsonFilePath, (err, data) => {
  			if (err) return reject(err);
  			resolve(data);
  		});
  	});
  
  	const jsonText = /** @type {string} */ (buf.toString());
  	// Strip comments to support JSONC (e.g., tsconfig.json with comments)
  	const jsonWithoutComments = stripComments
  		? stripJsonComments(jsonText, { trailingCommas: true, whitespace: true })
  		: jsonText;
  	return JSON.parse(jsonWithoutComments);
  }
  
  module.exports.readJson = readJson;