@sarahisweird/hmoog
Version:
Out-of-game automation for Hackmud
40 lines (39 loc) • 1.11 kB
JavaScript
import { watch as watchFile } from 'node:fs/promises';
export default class FileWatcher {
filePath;
listeners = [];
abortController;
constructor(filePath) {
this.filePath = filePath;
this.abortController = new AbortController();
this.listen().then();
}
waitForChange() {
return new Promise((resolve) => {
this.listeners.push(resolve);
});
}
close() {
this.abortController.abort();
}
async listen() {
try {
const watcher = watchFile(this.filePath, {
signal: this.abortController.signal,
persistent: true,
});
for await (const event of watcher) {
if (event.eventType !== 'change')
continue;
let listener;
while (listener = this.listeners.pop()) {
listener();
}
}
}
catch (error) {
if (!(error instanceof Error) || error.name !== 'AbortError')
throw error;
}
}
}