-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONFile.js
28 lines (22 loc) · 864 Bytes
/
JSONFile.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
const fs = require('fs').promises;
module.exports = class JSONFile {
constructor(path, jsonData = null) {
this.path = path;
this.jsonData = jsonData;
this.createFileIfNotExists().then(() => {
console.log(`JSON file '${this.path}' is ready to use`);
}).catch((err) => {
console.error(`Error creating JSON file '${this.path}': ${err}`);
});
}
async createFileIfNotExists() {
try {
await fs.access(this.path, fs.constants.F_OK);
}catch(err) {
await this.write(this.jsonData || {});
}
}
read = async () => JSON.parse(await fs.readFile(this.path, 'utf8'));
write = async data => fs.writeFile(this.path, JSON.stringify(data, null, 2));
modify = async jsonData => this.write({ ...await this.read(), ...jsonData });
}