This repository has been archived by the owner on Feb 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (97 loc) · 2.44 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*!
* refresh-config - index.js
* Copyright(c) 2014 dead_horse <[email protected]>
* MIT Licensed
*/
'use strict';
var debug = require('debug')('refresh-config');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var fs = require('fs');
var path = require('path');
/**
* expose `Config`
*/
module.exports = Config;
function Config(file) {
if (!(this instanceof Config)) {
return new Config(file);
}
this.file = path.resolve(file);
this.filename = path.basename(file);
this.dir = path.dirname(file);
debug('config base on %s', this.file);
this.watch();
this.data = {};
this.stale = {};
this.removed = [];
var content;
try {
content = fs.readFileSync(this.file, 'utf-8');
} catch (err) {
if (err.code !== 'ENOENT') {
debug('init error');
setImmediate(this.onerror.bind(this, err));
}
}
this.parse(content);
setImmediate(this.emit.bind(this, 'change'));
this.onerror = this.onerror.bind(this);
}
util.inherits(Config, EventEmitter);
Config.prototype.watch = function() {
if (this.watcher) {
return debug('already has dir watcher');
}
this.watcher = fs.watch(this.dir, {
persistent: true,
recursive: false
});
var self = this;
this.watcher.on('change', function (event, filename) {
if (filename !== self.filename) return;
self.onchange();
})
.on('error', this.onerror);
};
Config.prototype.onchange = function () {
debug('file %s changed', this.file);
var self = this;
fs.readFile(self.file, 'utf-8', function (err, content) {
if (err && err.code !== 'ENOENT') return self.emit('error', err);
if (err && err.code === 'ENOENT') debug('config file removed');
self.parse(content);
self.emit('change');
});
};
Config.prototype.parse = function (content) {
var data = {};
if (content) {
try {
data = JSON.parse(content);
} catch (err) {
debug('parse json content error');
return this.emit('error', err);
}
}
this.stale = this.data;
this.data = data;
this.removed = substract(this.data, this.stale);
};
Config.prototype.onerror = function(err) {
if (err) this.emit('error', err);
};
Config.prototype.close =
Config.prototype.destroy = function() {
this.watcher && this.watcher.close();
this.watcher = null;
};
function substract(fresh, stale) {
var removed = [];
for (var key in stale) {
if (fresh[key] === undefined) {
removed.push(key);
}
}
return removed;
}