-
Notifications
You must be signed in to change notification settings - Fork 0
/
Storage.js
43 lines (43 loc) · 1.03 KB
/
Storage.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
var fs = require('fs');
function Storage(file, construction = {}) {
try {
var target = JSON.parse(fs.readFileSync(file, 'utf8'));
if (construction.hasOwnProperty('constructor'))
construct(target);
} catch (e) {
var target = {};
}
return new Proxy(target, {
set: (target, property, value) => {
target[property] = value;
store();
},
deleteProperty: (target, property) => {
delete target[property];
store();
}
})
var dirty;
function store() {
if (dirty) return;
setTimeout(() => {
var json = target;
if (construction.destructor)
json = destruct(json);
fs.writeFile(file, JSON.stringify(json, undefined, '\t'), 'utf8', err => { if (err) console.log(err); });
dirty = false;
}, 0);
dirty = true;
}
function destruct(target) {
var json = {};
for (var name in target)
json[name] = construction.destructor(target[name]);
return json;
}
function construct(target) {
for (var name in target)
target[name] = new construction.constructor(target[name]);
}
}
module.exports = Storage;