Search code examples
node.jsnpmfile-watcherchokidar

npm chokidar firing event twice


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.


Solution

  • I used a global Array (processing_requests) to keep track of the handleFileRequest running for different files. and then before calling handleFileRequest I checked if this function is already running for the same file. If it's already running then I simply skip the execution of 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);
            }
        });