-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileWatcher.ts
More file actions
41 lines (36 loc) · 1.35 KB
/
Copy pathFileWatcher.ts
File metadata and controls
41 lines (36 loc) · 1.35 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
import { WatchEventType } from 'node:fs'
import { basename, dirname, join } from 'node:path/posix'
import { Path } from './types'
import { stat, watchChanges } from './Local'
import { LocalFileItem } from './FileSystem'
import ReferenceCountMap from './utils/ReferenceCountMap'
export default class {
constructor(private listener: (path: Path, stat: LocalFileItem|null, event?: WatchEventType) => void) {}
async watch(path: Path) {
if (this.watched.inc(path)) {
return
}
try {
const ac = new AbortController()
this.watched.set(path, ac)
for await (const {eventType, filename} of watchChanges(path, ac)) {
let newPath = path
if (eventType == "rename" && basename(path) !== filename) {
newPath = join(dirname(path), filename ?? '')
this.watched.renameKey(path, newPath)
}
try {
this.listener(path, stat(newPath), eventType)
} catch (e) {
this.listener(path, null, eventType)
}
}
} catch(e) {
console.error('Error while watch file', e)
}
}
unwatch(dir: Path) {
this.watched.dec(dir)?.abort()
}
private watched = new ReferenceCountMap<Path, AbortController>
}