-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFileWatcher.js
80 lines (62 loc) · 1.9 KB
/
FileWatcher.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
const fs = require('fs');
const LogTransformStream = require('./LogTransformStream');
class FileWatcher{
constructor(fileName){
this.fileName = fileName;
this.buffer = Buffer.alloc(1);
this.currentPosition = 0;
this.fd = null;
this.stat = null;
this.logTransformStream = new LogTransformStream();
}
async open() {
return new Promise((resolve, reject) => {
fs.open(this.fileName, 'r', (err, fd) => {
if(err) reject(err);
else resolve(fd);
});
});
}
watch(listener) {
console.log('Starting to watch', this.fileName);
fs.watch(this.fileName, listener);
}
attachListener(listener){
this.logTransformStream.on("data", (chunk)=> {
listener(chunk.toString());
});
}
async _read() {
}
updateStats(){
this.stat = fs.fstatSync(this.fd);
}
async read() {
const prevStat = this.stat;
this.updateStats();
const startPos = prevStat ? prevStat.size : 0;
const endPos = this.stat.size;
const sizeToRead = endPos - startPos;
const buffer = Buffer.alloc(sizeToRead);
if(startPos == endPos) {
return "";
}
return new Promise((resolve, reject) => {
fs.read(this.fd, buffer, 0, sizeToRead, startPos, function(err, bytesRead, buffer) {
if(err) reject(err);
else resolve(buffer.toString('utf-8'));
});
});
}
async start() {
this.fd = await this.open();
await this.read();
this.watch(async (event, filename) => {
if(event === 'change'){
const readData = await this.read();
this.logTransformStream.write(readData);
}
});
}
}
module.exports = FileWatcher;