-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (54 loc) · 1.78 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
const EventEmitter = require('events')
const fs = require('fs');
class Tail extends EventEmitter {
constructor({ filename }) {
super()
this.filename = filename
this.lastByte = 0;
this.data = '';
// let the user register the handler
setImmediate(this.init.bind(this))
}
init() {
try {
let { size } = fs.statSync(this.filename)
this.lastByte = size;
} catch (err) {
this.emit('error', err);
}
fs.watch(this.filename, { encoding: 'utf8' }, this.onWatch.bind(this));
}
onWatch(type) {
if (type === 'change' || type === 'rename') {
this.onFileChange();
}
}
onFileChange() {
fs.stat(this.filename, (err, { size: _currentByte }) => {
if (err) {
this.emit('error', err);
}
if (_currentByte > this.lastByte) {
let streamIn = fs.createReadStream(this.filename, { start: this.lastByte, encoding: 'utf8' });
streamIn.on('data', (_currentData) => {
this.data = this.data + _currentData;
this.lastByte = _currentByte;
})
streamIn.on('end', () => {
let regex = /\r?\n|\r/g
if (regex.exec(this.data)) {
this.data = this.data.replace(regex, "")
this.emit('line', this.data)
this.data = '';
}
})
} else {
// few content was removed from file
// so resetting it to last
this.lastByte = _currentByte;
}
})
}
}
module.exports = Tail;
module.exports.Tail = Tail;