-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.js
More file actions
57 lines (53 loc) · 1.41 KB
/
reader.js
File metadata and controls
57 lines (53 loc) · 1.41 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
const reader = require('readline');
const fs = require('fs');
const { Stream } = require('stream');
const linesSpeaker = (fileLocation, starting) => {
return new Promise((resolve, reject) => {
const linesReader = reader.createInterface({
input: fs.createReadStream(fileLocation, {
start: starting,
}),
output: new Stream(),
});
let extraLogLines = [];
linesReader.on('SIGTSTP', (err) => {
reject(err);
});
linesReader.on('line', (line) => {
extraLogLines.push(line.trim());
});
linesReader.on('close', () => {
if (extraLogLines.length > 10)
resolve(extraLogLines.slice(-10).join('\n'));
resolve(extraLogLines.join('\n'));
});
});
};
const attachFileReader = (LOG_FILE, io) => {
let resolver;
new Promise((resolve, _) => {
resolver = resolve;
}).then(() => {
console.log('file-check resolved');
fs.watchFile(LOG_FILE, (curr, prev) => {
if (curr.mtime === prev.mtime) return 0;
console.log('New content detected!');
linesSpeaker(
LOG_FILE,
prev.size < curr.size ? prev.size : curr.size
)
.then((lines) => io.emit('lines-update', lines))
.catch((err) => {
console.error(err);
io.emit('error', err);
});
return 0;
});
});
fs.open(LOG_FILE, 'a+', (err, content) => {
// a+ append flag avoids old data deletion
// file has been created; resolving the check
resolver();
});
};
module.exports = { linesSpeaker, attachFileReader };