-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.js
76 lines (54 loc) · 1.76 KB
/
listener.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
const fs = require('fs');
const endOfLine = require('os').EOL;
const initialBuffSize = 256;
module.exports = class Listener
{
constructor(file,callback){
this.file = file;
this.current = 0;
this.encoding = 'utf8';
this.callback = callback;
this.buffer = "";
this._generateFirstChunk();
}
_waitForEol(d){
this.buffer += d;
let idx = this.buffer.indexOf(endOfLine);
if(idx != -1 ){
this.callback(this.buffer.substring(0,idx));
this.buffer = this.buffer.substring(idx+endOfLine.length-1);
}
}
_beginWatch(){
fs.watch(this.file,(e,f)=>{
var size = fs.statSync(this.file).size;
if( size > this.current ){
let tmp = this.current;
this.current = size;
this._read(tmp,size-tmp,(d)=>this._waitForEol(d));
}
});
}
_generateFirstChunk(file){
var size = fs.statSync(this.file).size;
this.current = size;
if(size<=this.initialBuffSize)
{
this._read(0,size-1,this.callback,()=>this._beginWatch);
}else{
this._read(size-initialBuffSize,size-1,this.callback,()=>this._beginWatch());
}
}
_read(from,howmany,callback,then){
let stream = fs.createReadStream(this.file,{start:from,end:from+howmany-1});
stream.encoding = this.encoding;
stream.on('data',(data)=>{
callback(data.toString(this.encoding));
stream.close();
if(then !== undefined){
then();
}
}
);
}
}