File watcher — monitor file changes.
1const fs = require("fs");23class FileWatcher {4 constructor() {5 this.watchers = new Map();6 }78 watch(path, callback, options = {}) {9 const watcher = fs.watch(path, options, (eventType, filename) => {10 callback({11 type: eventType,12 file: filename,13 timestamp: Date.now(),14 });15 });1617 this.watchers.set(path, watcher);18 return () => this.unwatch(path);19 }2021 unwatch(path) {22 const watcher = this.watchers.get(path);23 if (watcher) {24 watcher.close();25 this.watchers.delete(path);26 }27 }2829 unwatchAll() {30 this.watchers.forEach(w => w.close());31 this.watchers.clear();32 }33}3435// Usage36const watcher = new FileWatcher();3738watcher.watch("./config", ({ type, file }) => {39 console.log(`File ${type}: ${file}`);40 if (file === "config.json") reloadConfig();41});
chokidar (more reliable):
1const chokidar = require("chokidar");2const watcher = chokidar.watch("./src", { ignoreInitial: true });3watcher.on("change", (path) => console.log("Changed:", path));