-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.js
30 lines (25 loc) · 791 Bytes
/
file.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
import fsLegacy from 'node:fs';
import fs from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { safeJsonParse } = require('tori');
export function isFileOrDirExisted(path) {
try {
fsLegacy.accessSync(path);
return true;
} catch {
return false;
}
}
export async function readFileAsJson(path) {
const str = await fs.readFile(path, { encoding: 'utf-8' });
return safeJsonParse(str, {});
}
export async function writeFileAsJson(path, obj) {
await fs.writeFile(path, JSON.stringify(obj, null, 2));
}
export async function replaceFileContent(path, fn) {
const content = await fs.readFile(path, { encoding: 'utf-8' });
const newContent = fn(content);
await fs.writeFile(path, newContent);
}