UNPKG

1.22 kBPlain TextView Raw
1import * as chokidar from "chokidar";
2
3export class FileWatcher {
4 public static async watch(paths: string | string[], sits: ("add" | "change" | "unlink")[], callback: (changedFiles: { type: string; filePath: string }[]) => void): Promise<void> {
5 await new Promise<void>(resolve => {
6 const watcher = chokidar.watch((typeof paths === "string" ? [paths] : paths).map(item => item.replace(/\\/g, "/")))
7 .on("ready", () => {
8 let preservedFileChanges: { type: string; filePath: string }[] = [];
9 let timeout: NodeJS.Timer;
10
11 const onWatched = (type: string, filePath: string) => {
12 preservedFileChanges.push({type, filePath});
13
14 clearTimeout(timeout);
15 timeout = setTimeout(
16 () => {
17 const fileChanges = Object.clone(preservedFileChanges);
18 preservedFileChanges = [];
19
20 callback(fileChanges);
21 },
22 300
23 );
24 };
25
26 for (const sit of sits) {
27 watcher.on(sit, filePath => {
28 onWatched(sit, filePath);
29 });
30 }
31
32 resolve();
33 });
34 });
35 }
36}
\No newline at end of file