-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathfile.js
43 lines (37 loc) · 1.06 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
import fs from 'node:fs';
import path from 'node:path';
export function appendFile(file, content) {
const parts = path.parse(file);
if (!fs.existsSync(parts.dir)) {
fs.mkdirSync(parts.dir, { recursive: true });
}
// TODO(joyeecheung): what if the file is a dir?
fs.appendFileSync(file, content, 'utf8');
};
export function writeFile(file, content) {
const parts = path.parse(file);
if (parts.dir !== '' && !fs.existsSync(parts.dir)) {
fs.mkdirSync(parts.dir, { recursive: true });
}
// TODO(joyeecheung): what if the file is a dir?
fs.writeFileSync(file, content, 'utf8');
};
export function writeJson(file, obj) {
writeFile(file, `${JSON.stringify(obj, null, 2)}\n`);
};
export function readFile(file) {
if (fs.existsSync(file)) {
return fs.readFileSync(file, 'utf8');
}
return '';
};
export function readJson(file) {
const content = readFile(file);
if (content) {
return JSON.parse(content);
}
return {};
};
export function removeDirectory(directory) {
return fs.promises.rm(directory, { recursive: true, force: true });
}