t-comm
Version:
专业、稳定、纯粹的工具库
44 lines (41 loc) • 1 kB
JavaScript
import { getFs } from '../nodejs/fs.mjs';
/**
* 解析带注释的 json 文件
* @param content 原始文件内容
* @returns json数据
* @example
* ```ts
* const text = `{
* // 这是一个注释
* "name": "foo",
* "version": "1.0.0" // 末尾注释
* }`;
* parseCommentJson(text); // { name: 'foo', version: '1.0.0' }
* ```
*/
function parseCommentJson(content) {
var newContent = content.replace(/(?:\s+|^)\/\/[^\n]*/g, '');
var json = {};
try {
json = JSON.parse(newContent);
} catch (err) {}
return json;
}
/**
* 获取带注释的 json 文件内容
* @param file 文件路径
* @returns json数据
* @example
* ```ts
* // tsconfig.json 中可能含有 // 注释
* const config = readCommentJson('./tsconfig.json');
* console.log(config.compilerOptions);
* ```
*/
function readCommentJson(file) {
var content = getFs().readFileSync(file, {
encoding: 'utf-8'
});
return parseCommentJson(content);
}
export { parseCommentJson, readCommentJson };