-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
FilesWatcher.ts
73 lines (64 loc) · 1.97 KB
/
FilesWatcher.ts
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
import * as chokidar from 'chokidar';
import * as path from 'path';
import startsWith = require('lodash/startsWith');
export class FilesWatcher {
watchPaths: string[];
watchExtensions: string[];
watchers: chokidar.FSWatcher[];
listeners: { [eventName: string]: Function[] };
constructor(watchPaths: string[], watchExtensions: string[]) {
this.watchPaths = watchPaths;
this.watchExtensions = watchExtensions;
this.watchers = [];
this.listeners = {};
}
isFileSupported(filePath: string) {
return this.watchExtensions.indexOf(path.extname(filePath)) !== -1;
}
watch() {
if (this.isWatching()) {
throw new Error('Cannot watch again - already watching.');
}
this.watchers = this.watchPaths.map((watchPath: string) => {
return chokidar
.watch(watchPath, { persistent: true, alwaysStat: true })
.on('change', (filePath: string, stats: any) => {
if (this.isFileSupported(filePath)) {
(this.listeners['change'] || []).forEach(changeListener => {
changeListener(filePath, stats);
});
}
})
.on('unlink', (filePath: string) => {
if (this.isFileSupported(filePath)) {
(this.listeners['unlink'] || []).forEach(unlinkListener => {
unlinkListener(filePath);
});
}
});
});
}
isWatchingFile(filePath: string) {
return (
this.isWatching() &&
this.isFileSupported(filePath) &&
this.watchPaths.some(watchPath => startsWith(filePath, watchPath))
);
}
isWatching() {
return this.watchers.length > 0;
}
on(event: string, listener: Function) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(listener);
}
off(event: string, listener: Function) {
if (this.listeners[event]) {
this.listeners[event] = this.listeners[event].filter(
oldListener => oldListener !== listener
);
}
}
}