-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
103 lines (87 loc) · 2.03 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
/**!
* changing - index.js
*
* Copyright(c) node-modules and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <[email protected]> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
const fs = require('fs');
const util = require('util');
const ms = require('humanize-ms');
const EventEmitter = require('events');
module.exports = Watcher;
function Watcher(options) {
if (!(this instanceof Watcher)) {
return new Watcher(options);
}
EventEmitter.call(this);
this.options = options || {};
this.options.interval = ms(this.options.interval || '10s');
// pathname: info
this._paths = {};
this._timer = setInterval(this._check.bind(this), this.options.interval);
}
util.inherits(Watcher, EventEmitter);
const proto = Watcher.prototype;
// on 'change' event
// on 'stat-error' event
proto.add = function (fullpath) {
if (!this._paths[fullpath]) {
this._paths[fullpath] = {
event: null,
path: fullpath,
stat: null,
errorMessage: null
};
this._checkPath(fullpath);
}
return this;
};
proto.close = function () {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
};
proto._check = function () {
for (let fullpath in this._paths) {
this._checkPath(fullpath);
}
};
proto._checkPath = function (fullpath) {
let info = this._paths[fullpath];
let that = this;
fs.lstat(fullpath, function (err, stat) {
if (err) {
if (info.errorMessage === err.message) {
// ignore this error
return;
}
info.errorMessage = err.message;
return that.emit('stat-error', err);
}
if (info.errorMessage) {
// error gone, need to emit change
info.errorMessage = null;
info.stat = stat;
info.event = 'change';
that.emit('change', info);
return;
}
if (!info.stat) {
info.stat = stat;
return;
}
if (info.stat.mtime.getTime() !== stat.mtime.getTime()) {
info.stat = stat;
info.event = 'change';
that.emit('change', info);
}
});
};