-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore.js
66 lines (61 loc) · 2.2 KB
/
datastore.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
const EventEmitter = require("events").EventEmitter;
const path = require('path');
const fs = require('fs');
const localdata = require('./localdata.js');
const logger = require('./logger.js');
class DataStore extends EventEmitter {
constructor(filename) {
super();
var that = this;
this.path = path.join(localdata.data_dir, filename);
fs.access(this.path, fs.constants.R_OK | fs.constants.W_OK, (err) => {
if(err) {
fs.writeFile(that.path, "{}", () => {
startWatch();
});
return;
}
startWatch();
});
function startWatch() {
fs.watch(that.path, 'utf8', (eventType, filename) => {
logger.debug('%s changed', filename);
that.load(function(err, filecontent) {
if(err) {
logger.error('Cannot fetch %s: %s', filename, err.message);
return;
}
logger.debug('%s reloaded', filename);
if(Object.keys(filecontent).length !== 0 || filecontent.constructor !== Object) {
that.emit('change', filecontent);
}
});
});
}
}
load(callback = () => {}) {
var that = this;
fs.readFile(this.path, 'utf8', (err, data) => {
if(err) {
if(err.code !== 'ENOENT') {
logger.warn('Failed to load %s: %s', that.path, err.message);
}
data = "{}";
}
try {
var obj = JSON.parse(data);
}
catch(e) {
var obj = {};
}
callback(null, obj);
});
}
save(obj, callback = (err) => err && logger.error('Failed to save: %s', err.message)) {
if(typeof obj !== 'object') {
return callback(new TypeError('Content should be an object', 'datastore.js'));
}
fs.writeFile(this.path, JSON.stringify(obj), 'utf8', callback);
}
}
var exports = module.exports = DataStore;