UNPKG

2.12 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const chokidar = require("chokidar");
4const path = require("path");
5class FilesWatcher {
6 constructor(watchPaths, watchExtensions) {
7 this.watchPaths = watchPaths;
8 this.watchExtensions = watchExtensions;
9 this.watchExtensions = watchExtensions;
10 this.watchers = [];
11 this.listeners = {};
12 }
13 isFileSupported(filePath) {
14 return this.watchExtensions.indexOf(path.extname(filePath)) !== -1;
15 }
16 watch() {
17 if (this.isWatching()) {
18 throw new Error('Cannot watch again - already watching.');
19 }
20 this.watchers = this.watchPaths.map((watchPath) => {
21 return chokidar
22 .watch(watchPath, { persistent: true, alwaysStat: true })
23 .on('change', (filePath, stats) => {
24 if (this.isFileSupported(filePath)) {
25 (this.listeners['change'] || []).forEach(changeListener => {
26 changeListener(filePath, stats);
27 });
28 }
29 })
30 .on('unlink', (filePath) => {
31 if (this.isFileSupported(filePath)) {
32 (this.listeners['unlink'] || []).forEach(unlinkListener => {
33 unlinkListener(filePath);
34 });
35 }
36 });
37 });
38 }
39 isWatchingFile(filePath) {
40 return (this.isWatching() &&
41 this.isFileSupported(filePath) &&
42 this.watchPaths.some(watchPath => filePath.startsWith(watchPath)));
43 }
44 isWatching() {
45 return this.watchers.length > 0;
46 }
47 on(event, listener) {
48 if (!this.listeners[event]) {
49 this.listeners[event] = [];
50 }
51 this.listeners[event].push(listener);
52 }
53 off(event, listener) {
54 if (this.listeners[event]) {
55 this.listeners[event] = this.listeners[event].filter(oldListener => oldListener !== listener);
56 }
57 }
58}
59exports.FilesWatcher = FilesWatcher;
60//# sourceMappingURL=FilesWatcher.js.map
\No newline at end of file