forked from TrainingByPackt/Professional-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilewatcher.js
More file actions
44 lines (41 loc) · 1.33 KB
/
filewatcher.js
File metadata and controls
44 lines (41 loc) · 1.33 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
const fs = require('fs').promises;
const EventEmitter = require('events');
class FileWatcher extends EventEmitter {
constructor(file, delay) {
super();
this.timeModified = undefined;
this.file = file;
this.delay = delay;
this.watchTimer = undefined;
}
startWatch() {
if (!this.watchTimer) {
this.watchTimer = setInterval(() => {
fs.stat(this.file).then((stat) => {
if (this.timeModified !== stat.mtime.toString()) {
fs.readFile(this.file, 'utf-8').then((content) => {
this.emit('change', content);
}).catch((error) => {
this.emit('error', error);
});
this.timeModified = stat.mtime.toString();
}
}).catch((error) => {
this.emit('error', error);
});
}, this.delay);
}
}
stopWatch() {
if (this.watchTimer) {
clearInterval(this.watchTimer);
this.watchTimer = undefined;
}
}
}
const watcher = new FileWatcher('test.txt', 1000);
watcher.on('error', console.error);
watcher.on('change', (change) => {
console.log('new change:', change);
});
watcher.startWatch();