[英]npm chokidar firing event twice
I'm using the NPM package chokidar to watch for the new files.我正在使用 NPM package chokidar 来监视新文件。 I want to execute a function whenever a new file is created or an existing file is updated.
我想在创建新文件或更新现有文件时执行 function。 The problem is whenever a new file is created the chokidar NPM package fires 2 events that are
add
and change
.问题是每当创建新文件时,chokidar NPM package 都会触发
add
和change
两个事件。 Which makes the function execute 2 times.这使得 function 执行了 2 次。
I tried to add listeners in 2 ways.我尝试以两种方式添加听众。
Method 1方法一
watcher.on('add', handleFileRequest);
watcher.on('change', handleFileRequest);
Method 2方法二
watcher.on('all', (event, path) => {
console.log(`event: ${event}`);
if (event == 'change' || event == 'add') {
handleFileRequest(path);
}
});
Both of the above code snippets call the handleFileRequest method 2 times.以上两个代码片段都调用了 handleFileRequest 方法 2 次。
I used a global Array ( processing_requests
) to keep track of the handleFileRequest
running for different files.我使用全局数组 (
processing_requests
) 来跟踪针对不同文件运行的handleFileRequest
。 and then before calling handleFileRequest
I checked if this function is already running for the same file.然后在调用
handleFileRequest
之前,我检查了这个 function 是否已经在为同一个文件运行。 If it's already running then I simply skip the execution of handleFileRequest
.如果它已经在运行,那么我只是跳过
handleFileRequest
的执行。
watcher.on('all', (event, path) => {
if ((event == 'change' || event == 'add') && !processing_requests.includes(path)) {
processing_requests.push(path);
handleFileRequest(path);
setTimeout(function() {
processing_requests = processing_requests.filter(x => x != path);
}, 500);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.