-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtinystore.js
37 lines (32 loc) · 830 Bytes
/
tinystore.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
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var fs = require('fs');
var TinyStore = function(path){
this.path = path;
};
util.inherits(TinyStore, EventEmitter);
TinyStore.prototype.set = function(key, value, callback){
var json;
try {
var content = fs.readFileSync(this.path, { encoding: 'utf-8' });
json = JSON.parse(content);
} catch (e){
json = {};
}
if (value !== json[key]){
json[key] = value;
this.emit('change', key, value);
}
fs.writeFile(this.path, JSON.stringify(json), callback);
};
TinyStore.prototype.get = function(key, callback){
var content;
try {
content = fs.readFileSync(this.path, { encoding: 'utf-8' });
} catch (e){
return null;
}
var json = JSON.parse(content);
return json[key];
};
module.exports = TinyStore;