-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
63 lines (51 loc) · 1.84 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
// -----------------------------------------------------
// This file sets up the module for tail; It does every-
// thing except detect file size changes, which is
// implemented by the filewatcher module.
// -----------------------------------------------------
var fs = require('fs'),
fileWatcher = require('file-size-watcher');
module.exports = {
startTailing: function(options) {
var fd = typeof options == "string" ? options : "";
options = typeof options == "object" ? options : {};
options.interval = options.interval || 100;
options.mode = options.mode || 'lines';
options.onErr = options.onErr || null;
options.onReady = options.onReady || null;
// Allow null encoding for raw binary (want to write a unit test for this case? :D).
options.encoding = typeof options.encoding == "undefined" ? 'utf-8' : options.encoding;
fd = fd || options.fd;
var ms = options.interval,
mode = options.mode,
encoding = options.encoding,
fileTailer = fileWatcher.watch(fd, ms, options.OnErr, options.onReady);
fileTailer.conf = options; // expose these to user.
// Convenience event. Also prevents halts if user is not catching errors
fileTailer.on('error',function(e) {
if (!(e.code && e.code == "ENOENT")) {
fileTailer.emit('tailError', e);
};
});
fileTailer.on('sizeChange', function(newSize, oldSize) {
if ((newSize-oldSize) > 0) {
var stream = fs.createReadStream(fd,{
encoding:encoding,
start:oldSize,
end:newSize
});
if (mode == "lines") {
stream.on('data', function(chunk) {
var lines = chunk.toString().trim().split('\n');
for( var i = 0; i < lines.length; i++ ){
fileTailer.emit('line', lines[i]);
}
});
} else {
fileTailer.emit('stream', stream);
}
}
});
return fileTailer;
}
};