-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathdatabase.js
70 lines (62 loc) · 1.7 KB
/
database.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
58
59
60
61
62
63
64
65
66
67
68
69
70
const fs = require("fs");
function onExit(obj, e) {
fs.writeFileSync(obj.path, JSON.stringify(obj.jObj));
if (typeof e == "object") {
console.log(e);
} else if (e == "SIGINT") {
process.exit();
}
}
class database {
path = "";
jObj = {};
constructor(db_path, autosave=true) {
if (!fs.existsSync(db_path)) {
fs.writeFileSync(db_path, "{}");
}
{
let str = fs.readFileSync(db_path);
this.jObj = JSON.parse(str != "" && str || "{}");
this.path = db_path;
}
if (autosave) {
let obj = this;
process.on('beforeExit', ()=>onExit(obj));
process.on('SIGINT', ()=>onExit(obj, "SIGINT"));
process.on('uncaughtException', (e)=>onExit(obj, e));
}
}
save = function() {
fs.writeFileSync(this.path, JSON.stringify(this.jObj));
}
assureValueExists = function(path, value) {
let obj = this.jObj;
let sp = path.split("/");
let plen = sp.length;
sp.forEach((v,i) => {
if (obj[v] == undefined && plen-1 == i)
obj[v] = value;
if (obj[v] == undefined)
obj[v] = {};
obj = obj[v];
});
}
getValue = function(path) {
let obj = this.jObj;
path.split("/").forEach(v => {
obj = obj[v];
});
return obj;
}
setValue = function(path, value) {
let obj = this.jObj;
let sp = path.split("/");
let key = sp.pop();
sp.forEach(v => {
obj = obj[v];
});
obj[key] = value;
return obj;
}
}
module.exports = database;