chokidar
chokidar
是一个功能强大、跨平台、性能优秀的 文件系统监听库,适用于 Node.js 环境,底层使用原生 fs.watch
和 fs.watchFile
,并在 macOS/Linux 上优先使用更高效的 fsevents
(若可用)。
基本用法:
import chokidar from 'chokidar';// 监听单个文件或目录
const watcher = chokidar.watch('./some-folder-or-file', {ignoreInitial: true, // 不触发初始的 add/addDir 事件
});// 注册事件监听器
watcher.on('add', path => console.log(`📄 文件添加: ${path}`)).on('change', path => console.log(`✏️ 文件修改: ${path}`)).on('unlink', path => console.log(`❌ 文件删除: ${path}`)).on('addDir', path => console.log(`📁 目录添加: ${path}`)).on('unlinkDir', path => console.log(`🗑️ 目录删除: ${path}`));
监听多个文件
chokidar.watch(['src/**/*.js', 'assets/**/*'], {ignored: /(^|[\/\\])\../, // 忽略 . 开头的隐藏文件
});
停止监听
watcher.close().then(() => console.log('已停止监听'));