Skip to content

Commit

Permalink
Fix return dropped event 'delete' and update code style
Browse files Browse the repository at this point in the history
  • Loading branch information
timursevimli committed Jan 9, 2024
1 parent 77e15ce commit a3a8c84
Showing 1 changed file with 16 additions and 19 deletions.
35 changes: 16 additions & 19 deletions metawatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,37 +58,39 @@ class DirectoryWatcher extends EventEmitter {
this.emit('after', queue);
}

watchDirectory(dirPath) {
if (this.watchers.has(dirPath)) return;
const watcher = fs.watch(dirPath);
watcher.on('error', () => void this.unwatch(dirPath));
watcher.on('change', (_, fileName) => {
const target = dirPath.endsWith(path.sep + fileName);
const filePath = target ? dirPath : path.join(dirPath, fileName);
watchDirectory(targetPath) {
if (this.watchers.has(targetPath)) return;
const watcher = fs.watch(targetPath);
watcher.on('error', () => void this.unwatch(targetPath));
watcher.on('change', (...args) => {
const fileName = args.pop();
const target = targetPath.endsWith(path.sep + fileName);
const filePath = target ? targetPath : path.join(targetPath, fileName);
if (this.isExcludedFile(filePath)) return;
this.post('*', filePath);
fs.stat(filePath, (err, stats) => {
if (err) {
const keys = [...this.watchers.keys()];
this.unwatch(filePath);
this.post('delete', filePath);
const event = keys.includes(filePath) ? 'unlinkDir' : 'unlink';
this.post(event, filePath);
return void this.unwatch(filePath);
return void this.post(event, filePath);
}
if (stats.isDirectory()) this.watch(filePath);
this.post('change', filePath);
});
});
this.watchers.set(dirPath, watcher);
this.watchers.set(targetPath, watcher);
}

unwatch(filePath) {
const watcher = this.watchers.get(filePath);
unwatch(path) {
const watcher = this.watchers.get(path);
if (!watcher) return;
watcher.close();
this.watchers.delete(filePath);
this.watchers.delete(path);
}

watch(targetPath = process.cwd()) {
watch(targetPath) {
if (this.isExcludedDir(targetPath)) return this;
fs.readdir(targetPath, { withFileTypes: true }, (err, files) => {
if (err) return this;
Expand All @@ -102,11 +104,6 @@ class DirectoryWatcher extends EventEmitter {
});
return this;
}

stop(filePath) {
if (filePath) return void this.unwatch(filePath);
for (const [filePath] of this.watchers) this.unwatch(filePath);
}
}

module.exports = { DirectoryWatcher };

0 comments on commit a3a8c84

Please sign in to comment.