-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefStore.js
76 lines (62 loc) · 2.07 KB
/
prefStore.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
71
72
73
74
75
module.exports = PrefStore;
var fs = require('fs'),
path = require('path'),
objectAssign = require('object-assign'),
argConverter = require('./argConverter');
var home = process.env.HOME || process.env.USERPROFILE;
prefsPath = path.resolve(home, './.timecard_prefs'),
loadingErrorMsg = 'Cannot read or write prefs until PrefStore has loaded. Uses the constructor callback parameter.';
function PrefStore(cb) {
var prefs = this;
fs.readFile(prefsPath, {
encoding: 'utf8'
}, function (err, data) {
if (err) {
if (err.code === 'ENOENT') {
prefs._prefsObj = {};
} else {
cb(err);
return;
}
} else {
try {
prefs._prefsObj = JSON.parse(data);
} catch (e) {
var msg = 'Corrupt prefs file \'' + prefsPath + '\'. Could not parse as JSON.';
cb(new Error(msg));
return;
}
}
cb(null, prefs);
});
}
PrefStore.prototype.read = function (key) {
if (!this._prefsObj) throw new Error(loadingErrorMsg);
return this._prefsObj[key];
};
PrefStore.prototype.write = function (key, val, cb) {
if (!this._prefsObj) throw new Error(loadingErrorMsg);
var newPrefs = objectAssign({}, this._prefsObj);
// NOTE: We write all values as strings. We handle converting to the correct type on read.
newPrefs[key] = val.toString();
this._writePrefsObj(newPrefs, cb);
};
PrefStore.prototype.remove = function (key, cb) {
if (!this._prefsObj) throw new Error(loadingErrorMsg);
var newPrefs = objectAssign({}, this._prefsObj);
delete newPrefs[key];
this._writePrefsObj(newPrefs, cb);
};
PrefStore.prototype._writePrefsObj = function (newPrefs, cb) {
fs.writeFile(prefsPath, JSON.stringify(newPrefs, null, 2), function (err) {
if (err) {
if (cb) {
cb(err);
return;
}
throw err;
}
this._prefsObj = newPrefs;
if (cb) cb();
});
};