UNPKG

mcp-extended-tools

Version:
70 lines (58 loc) 1.85 kB
const chokidar = require('chokidar'); const { EventEmitter } = require('events'); const path = require('path'); class FileWatcher extends EventEmitter { constructor() { super(); this.watchers = new Map(); } watch(options = {}) { const { paths = ['.'], ignore = ['**/node_modules/**', '**/.git/**'], watchId = Date.now().toString() } = options; if (this.watchers.has(watchId)) { throw new Error(`Watch with ID ${watchId} already exists`); } const watcher = chokidar.watch(paths, { ignored: ignore, persistent: true, ignoreInitial: true }); watcher .on('add', path => this.emit('file-event', { watchId, type: 'add', path })) .on('change', path => this.emit('file-event', { watchId, type: 'change', path })) .on('unlink', path => this.emit('file-event', { watchId, type: 'delete', path })) .on('error', error => this.emit('error', { watchId, error: error.message })); this.watchers.set(watchId, watcher); return watchId; } unwatch(watchId) { const watcher = this.watchers.get(watchId); if (watcher) { watcher.close(); this.watchers.delete(watchId); return true; } return false; } listWatchers() { return Array.from(this.watchers.keys()); } cleanup() { for (const [id, watcher] of this.watchers) { watcher.close(); } this.watchers.clear(); } } // Create singleton instance const watcher = new FileWatcher(); // Cleanup on exit process.on('SIGINT', () => watcher.cleanup()); process.on('SIGTERM', () => watcher.cleanup()); module.exports = { FileWatcher, watcher };