forked from sdwilsh/tree-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsondb.js
38 lines (35 loc) · 952 Bytes
/
jsondb.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
var fs = require("fs");
function Config(path)
{
this.path = path;
this.db = JSON.parse(fs.readFileSync(path, 'utf8'));
}
Config.prototype = {
isDirty: false,
saveInProgress: false,
markDirty: function () {
this.isDirty = true;
if (!this.saveInProgress)
this.save();
},
save: function () {
this.saveInProgress = true;
var count = Object.keys(this.db).length;
fs.writeFile(this.path, JSON.stringify(this.db, null, ' '), 'utf8', this._saveComplete.bind(this, count));
this.isDirty = false;
},
_saveComplete: function (count, err) {
if (err) {
console.error("Got error trying to save database to " + this.path + ": " + e);
} else {
console.log("Saved new version of database to " + this.path + " with " + count + " entries");
}
this.saveInProgress = false;
if (this.isDirty) {
this.save();
}
}
};
module.exports = function (path) {
return new Config(path);
}