设计思路
- 使用防抖(Debounce)策略:为了合并短时间内频繁的文件修改操作,采用防抖机制。当文件修改事件触发时,设置一个定时器,若在定时器规定时间内再次触发相同文件的修改事件,则清除之前的定时器并重新设置,确保只有在一段时间内没有新的修改事件触发时,才执行通知操作。
- 维护文件状态:为了保证通知内容准确,需要维护每个文件的状态。在文件变化时,记录变化的类型(创建、修改、删除等)以及相关的详细信息。
关键代码片段
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');
// 用于存储文件变化状态的对象
const fileStatus = {};
// 防抖函数
function debounce(func, delay) {
let timer;
return function(...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 通知函数
const notify = debounce(() => {
if (Object.keys(fileStatus).length === 0) return;
console.log('文件变化通知:', fileStatus);
// 重置文件状态
fileStatus = {};
}, 500); // 500毫秒内合并通知
const watcher = chokidar.watch('.', {
ignored: /(^|[\/\\])\../, // 忽略隐藏文件
persistent: true
});
watcher
.on('add', (path) => {
fileStatus[path] = { type: 'add', path };
notify();
})
.on('change', (path) => {
fileStatus[path] = { type: 'change', path };
notify();
})
.on('unlink', (path) => {
fileStatus[path] = { type: 'unlink', path };
notify();
});