-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwatchdir.js
82 lines (61 loc) · 2.06 KB
/
watchdir.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
var fs = require("fs");
var util = require("util");
var path = require("path");
var EventEmitter = require("events").EventEmitter;
function WatchDir(options){
EventEmitter.call(this);
this._dirs = {};
this.options = options || {};
var _this = this;
this.onWatch = function (event, filename) {
_this.emit("change",event, filename);
if("rename") _this.add(filename);
};
}
util.inherits(WatchDir, EventEmitter);
WatchDir.prototype.removeAll = function(){
for(var file in this._dirs){
this._dirs[file].close();
delete this._dirs[file];
}
};
WatchDir.prototype.remove = function(dirname){
dirname = path.resolve(dirname);
for(var file in this._dirs){
if( file.indexOf(dirname) === 0){
//console.log("remove %s",dirname);
this._dirs[file].close();
delete this._dirs[file];
}
}
};
WatchDir.prototype.add = function(dirname){
dirname = path.resolve(dirname);
var _this = this;
(function add(dirname){
fs.exists(dirname, function(exists){
if(exists){
fs.lstat(dirname,function(err, stats) {
if(err || !stats.isDirectory() ) return;
if(!(dirname in _this._dirs)){
_this._dirs[dirname] = fs.watch(dirname, _this.options.watch || {} ,
function (event, filename) {
_this.onWatch(event, path.resolve(dirname,filename ));
});
}
fs.readdir(dirname, function(err, files) {
//console.log("add %s", dirname);
files.forEach(function(file){
add(path.resolve(dirname,file));
});
});
});
}else{
_this.remove(dirname);
}
});
})(dirname);
};
module.exports = function(options){
return new WatchDir(options);
};