-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathjson-store.js
57 lines (49 loc) · 1.19 KB
/
json-store.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
const fs = require('fs');
function replacer(key, value) {
if(key[0] !== '$' ) return value
}
class JSONStore {
constructor(filePath) {
this.filePath = filePath;
this.data = {};
// Load data from file if it exists
this.load();
}
load() {
if( !fs.existsSync(this.filePath) ) {
fs.writeFileSync(this.filePath, '{}');
}
try {
const data = fs.readFileSync(this.filePath);
this.data = JSON.parse(data);
} catch (err) {
console.error('Error loading data:', err);
throw err
}
}
save() {
try {
const data = JSON.stringify(this.data, replacer, 2);
fs.writeFileSync(this.filePath, data);
} catch (err) {
console.error('Error saving data:', err);
}
}
read(key, defaults) {
let data = this.data[key];
if( !data ) {
data = defaults()
this.write(key, data)
}
return data
}
write(key, value) {
this.data[key] = value;
this.save();
}
}
module.exports = {
create(filepath) {
return new JSONStore(filepath)
}
}