UNPKG

653 BJavaScriptView Raw
1import {readFileSync, promises as fs} from 'node:fs';
2
3const {readFile} = fs;
4
5const parse = (buffer, {beforeParse, reviver} = {}) => {
6 // Unlike `buffer.toString()` and `fs.readFile(path, 'utf8')`, `TextDecoder`` will remove BOM.
7 let data = new TextDecoder().decode(buffer);
8
9 if (typeof beforeParse === 'function') {
10 data = beforeParse(data);
11 }
12
13 return JSON.parse(data, reviver);
14};
15
16export async function loadJsonFile(filePath, options) {
17 const buffer = await readFile(filePath);
18 return parse(buffer, options);
19}
20
21export function loadJsonFileSync(filePath, options) {
22 const buffer = readFileSync(filePath);
23 return parse(buffer, options);
24}