-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
index.js
87 lines (72 loc) · 2.13 KB
/
index.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import path from 'node:path';
import fs, {promises as fsPromises} from 'node:fs';
import writeFileAtomic from 'write-file-atomic';
import sortKeys from 'sort-keys';
import detectIndent from 'detect-indent';
import isPlainObj from 'is-plain-obj';
const init = (function_, filePath, data, options) => {
if (!filePath) {
throw new TypeError('Expected a filepath');
}
if (data === undefined) {
throw new TypeError('Expected data to stringify');
}
options = {
indent: '\t',
sortKeys: false,
...options,
};
if (options.sortKeys && isPlainObj(data)) {
data = sortKeys(data, {
deep: true,
compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined,
});
}
return function_(filePath, data, options);
};
const main = async (filePath, data, options) => {
let {indent} = options;
let trailingNewline = '\n';
try {
const file = await fsPromises.readFile(filePath, 'utf8');
if (!file.endsWith('\n')) {
trailingNewline = '';
}
if (options.detectIndent) {
indent = detectIndent(file).indent;
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const json = JSON.stringify(data, options.replacer, indent);
return writeFileAtomic(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
};
const mainSync = (filePath, data, options) => {
let {indent} = options;
let trailingNewline = '\n';
try {
const file = fs.readFileSync(filePath, 'utf8');
if (!file.endsWith('\n')) {
trailingNewline = '';
}
if (options.detectIndent) {
indent = detectIndent(file).indent;
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const json = JSON.stringify(data, options.replacer, indent);
return writeFileAtomic.sync(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
};
export async function writeJsonFile(filePath, data, options) {
await fsPromises.mkdir(path.dirname(filePath), {recursive: true});
await init(main, filePath, data, options);
}
export function writeJsonFileSync(filePath, data, options) {
fs.mkdirSync(path.dirname(filePath), {recursive: true});
init(mainSync, filePath, data, options);
}