-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathfile-watcher.ts
More file actions
55 lines (49 loc) · 1.53 KB
/
file-watcher.ts
File metadata and controls
55 lines (49 loc) · 1.53 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
import chokidar from 'chokidar';
export interface FileWatcherOptions {
rootPath: string;
/** ms after last change before triggering. Default: 2000 */
debounceMs?: number;
/** Called once the debounce window expires after the last detected change */
onChanged: () => void;
}
/**
* Watch rootPath for source file changes and call onChanged (debounced).
* Returns a stop() function that cancels the debounce timer and closes the watcher.
*/
export function startFileWatcher(opts: FileWatcherOptions): () => void {
const { rootPath, debounceMs = 2000, onChanged } = opts;
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
const trigger = () => {
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debounceTimer = undefined;
onChanged();
}, debounceMs);
};
const watcher = chokidar.watch(rootPath, {
ignored: [
'**/node_modules/**',
'**/.codebase-context/**',
'**/.git/**',
'**/dist/**',
'**/.nx/**',
'**/.planning/**',
'**/coverage/**',
'**/.turbo/**',
'**/.next/**',
'**/.cache/**'
],
persistent: true,
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 }
});
watcher
.on('add', trigger)
.on('change', trigger)
.on('unlink', trigger)
.on('error', (err: unknown) => console.error('[file-watcher] error:', err));
return () => {
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
void watcher.close();
};
}