-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjson-store.js
More file actions
47 lines (38 loc) · 992 Bytes
/
Copy pathjson-store.js
File metadata and controls
47 lines (38 loc) · 992 Bytes
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
var fs = require('fs');
function Store(path) {
this.path = path;
if (!fs.existsSync(path))
fs.writeFileSync(path, JSON.stringify({}));
this.Store = require(path);
}
Store.prototype.get = function(key) {
if (!key) return clone(this.Store);
if (!this.Store[key]) return;
return clone(this.Store[key]);
}
Store.prototype.set = function(key, value) {
this.Store[key] = clone(value);
}
Store.prototype.setSync = function(key, value) {
this.Store[key] = clone(value);
this.saveSync();
}
Store.prototype.del = function(key) {
delete this.Store[key];
}
Store.prototype.delSync = function(key) {
delete this.Store[key];
this.saveSync();
}
Store.prototype.save = function() {
fs.writeFile(this.path, JSON.stringify(this.Store));
}
Store.prototype.saveSync = function() {
fs.writeFileSync(this.path, JSON.stringify(this.Store));
}
function clone(data) {
return JSON.parse(JSON.stringify(data));
}
module.exports = function(path) {
return new Store(path);
}