Repository navigation
Expand file tree
/
Copy pathtailer.js
More file actions
112 lines (105 loc) · 2.34 KB
/
Copy pathtailer.js
File metadata and controls
112 lines (105 loc) · 2.34 KB
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
var fs = require('fs');
var async = require('async');
module.exports = Tailer;
var READBYTES = 1024;
function Tailer(file, options){
this.file = file;
this.delay = 1000;
this.fromstart = false;
this.stop = false;
if(options && undefined !== options.delay){
this.delay = options.delay;
}
if(options && undefined !== options.fromstart){
this.fromstart = options.fromstart;
}
}
Tailer.prototype = {
tail: function(thecallback){
var _this = this;
_this.buffer = new Buffer(READBYTES);
_this.lines = "";
async.waterfall([
function(callback){
fs.stat(_this.file, function(err, stats){
if(err){
callback(err);
}else{
callback(null, stats.size);
}
});
},
function(size, callback){
fs.open(_this.file, 'r', function(err, fd){
if(err){
callback(err);
}else{
callback(null, fd, size);
}
});
},
function(fd, size, callback){
_this.fd = fd;
_this.offset = _this.fromstart?0:size;
setTimeout(function(){
return _this.readfile(thecallback);
}, _this.delay);
}
], function(err, result){
if(err){
thecallback(err);
}
});
},
untail: function(){
var _this = this;
_this.stop = true;
},
readfile: function(thecallback){
var _this = this;
var _bytesread = READBYTES;
_this.lines = "";
async.series([
function(callback){
fs.stat(_this.file, function(err, stats){
if(err){
callback(err);
}else{
if(stats.size < _this.offset){
//File seems to be truncated, reset offset
_this.offset = 0;
}
callback(null);
}
});
},
function(seriescallback){
async.whilst(function(){
return (_bytesread == READBYTES) && !_this.stop;
},
function(callback){
fs.read(_this.fd, _this.buffer, 0, READBYTES, _this.offset, function(err, bytesread, buffer){
_bytesread = bytesread;
_this.offset += bytesread;
_this.lines += _this.buffer.slice(0, bytesread).toString('utf8');
callback(err);
});
},
function(err){
var lines = _this.lines.split("\n");
for(var i = 0; i < lines.length - 1; i++){
thecallback(null, lines[i]);
}
setTimeout(function(){
return _this.readfile(thecallback);
}, _this.delay);
seriescallback(null);
});
}
], function(err, results){
if(err){
thecallback(err);
}
});
}
};