-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
85 lines (72 loc) · 1.93 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
var events = require('events'),
fs = require('fs');
function checkFileSize (fn, oldSize, cb, onErr) {
fs.stat(fn, function(error, info){
if (error) {
onErr(error);
// If file missing, we'll just say it's size changed to 0.
// The ENOENT will also be emitted.
if (error.code=="ENOENT") {
if(0 != oldSize){
cb(0);
}
};
} else {
if(info.size != oldSize){
cb(info.size);
}
}
});
}
module.exports = {
watch: function(fd, ms, onErr, onReady){
ms = ms || 100;
var watcher = new events.EventEmitter(),
currSize = -1,
pulse,
fileSizeChangeHandler,
errorHandler,
check;
// -------------------------------------------------------
// Ignored 'error' events will cause the program to crash.
// Do not let this happen.
// -------------------------------------------------------
onErr = onErr || function() {};
// -------------------------------------------------------
// Without these, the user might run into race conditions
// with those initial events.
// -------------------------------------------------------
if (onErr) watcher.on('error', onErr);
if (onReady) watcher.on('ready', onReady);
fileSizeChangeHandler = function(newSize) {
if(currSize !== -1){
watcher.emit('sizeChange', newSize, currSize);
} else {
watcher.emit('ready', newSize);
}
currSize = newSize;
};
errorHandler = function(error) {
watcher.emit('error',error);
onErr(error);
};
check = function(){
checkFileSize(fd, currSize, fileSizeChangeHandler, errorHandler);
};
watcher.go = function() {
pulse = setInterval( check, (ms || 1000));
};
watcher.stop = function() {
pulse && clearInterval(pulse);
};
watcher.info = function() {
return {
size: currSize
};
};
// Immediately check file size to set baseline. Then start watching on an interval.
check();
watcher.once('ready',function() { watcher.go(); });
return watcher;
}
};