forked from jairajs89/zerver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.js
124 lines (105 loc) · 2.62 KB
/
watcher.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
120
121
122
123
124
var fs = require('fs'),
path = require('path'),
stalker = require('stalker');
exports.watch = function (dir, callback) {
var filesNames = findSync(dir),
files = {};
filesNames.forEach(function (fileName) {
setupWatcher(fileName);
});
stalker.watch(
dir,
function (err, fileName) {
setupWatcher(fileName);
changeDetected(fileName);
},
function (err, fileName) {
destroyWatcher(fileName);
changeDetected(fileName);
}
);
function setupWatcher (fileName) {
if ( files[fileName] ) {
return;
}
var watcher;
if (fs.watch) {
watcher = fs.watch(fileName, function () {
changeDetected(fileName);
});
}
else {
fs.watchFile(fileName, function () {
changeDetected(fileName);
});
watcher = true;
}
files[fileName] = watcher;
}
function destroyWatcher (fileName) {
var watcher = files[fileName];
if ( !watcher ) {
return;
}
if (watcher !== true) {
watcher.close();
}
else {
fs.unwatchFile(fileName);
}
delete files[fileName];
}
function changeDetected (fileName) {
callback(fileName);
}
};
// taken from [email protected]
// wasnt included as a dependency because its
// devDependencies tend to take *really* long
// to install with all that C compilation.
function createInodeChecker () {
var inodes = {};
return function inodeSeen(inode) {
if (inodes[inode]) {
return true;
} else {
inodes[inode] = true;
return false;
}
}
}
function findSync (dir, options, callback) {
cb = arguments[arguments.length - 1];
if (typeof(cb) !== 'function') {
cb = undefined;
}
var inodeSeen = createInodeChecker();
var files = [];
var fileQueue = [];
var processFile = function processFile(file) {
var stat = fs.lstatSync(file);
if (inodeSeen(stat.ino)) {
return;
}
files.push(file);
cb && cb(file, stat)
if (stat.isDirectory()) {
fs.readdirSync(file).forEach(function(f) { fileQueue.push(path.join(file, f)); });
} else if (stat.isSymbolicLink()) {
if (options && options.follow_symlinks && path.existsSync(file)) {
fileQueue.push(fs.realpathSync(file));
}
}
};
/* we don't include the starting directory unless it is a file */
var stat = fs.lstatSync(dir);
if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(function(f) { fileQueue.push(path.join(dir, f)); });
} else {
fileQueue.push(dir);
}
while (fileQueue.length > 0) {
processFile(fileQueue.shift());
}
return files;
};