I'm using the NPM package chokidar to watch for the new files. I want to execute a function whenever a new file is created or an existing file is updated.
The problem is whenever a new file is created the chokidar NPM package fires 2 events that are add and change. Which makes the function execute 2 times.
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.
I used a global Array (
processing_requests) to keep track of thehandleFileRequestrunning for different files. and then before callinghandleFileRequestI checked if this function is already running for the same file. If it's already running then I simply skip the execution ofhandleFileRequest.