forked from e-dant/watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.ts
61 lines (56 loc) · 1.42 KB
/
watcher.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
import { createRequire } from "node:module";
const wcw = createRequire(import.meta.url)("../build/Release/watcher-napi.node");
export enum PathType {
dir = 'dir',
file = 'file',
hardLink = 'hardLink',
symLink = 'symLink',
watcher = 'watcher',
other = 'other',
}
export enum EffectType {
rename = 'rename',
modify = 'modify',
create = 'create',
destroy = 'destroy',
owner = 'owner',
other = 'other',
}
export interface Event {
effectTime: number;
pathName: string;
effectType: EffectType;
pathType: PathType;
associatedPathName: string | null;
}
interface CEvent {
effectTime: number;
pathName: string;
associatedPathName: string | null;
effectType: number;
pathType: number;
}
export const watch = (path: string, cb: (event: Event) => void): { close: () => boolean } => {
let typedCb: null | ((_: CEvent) => void) = (cEvent) => {
let event: Event = {
effectTime: cEvent.effectTime,
pathName: cEvent.pathName,
associatedPathName: cEvent.associatedPathName,
effectType: Object.keys(EffectType)[cEvent.effectType] as EffectType,
pathType: Object.keys(PathType)[cEvent.pathType] as PathType,
};
cb(event);
};
let watcher = wcw.watch(path, typedCb);
return {
close: (): boolean => {
if (!watcher || !typedCb) {
return false;
}
const ok = watcher.close();
watcher = null;
typedCb = null;
return ok;
}
};
}