diff --git a/metawatch.js b/metawatch.js index 46c397c..3549c30 100644 --- a/metawatch.js +++ b/metawatch.js @@ -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; @@ -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 };