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.