Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Filesystem Watch throwing event twice or more often

I'm watching the config files of my NodeJS server on Ubuntu using:

for( var index in cfgFiles ) {
    fs.watch(cfgFiles[index], function(event, fileName) {
        logger.info("======> EVENT: " + event);
        updateConfigData(fileName);
    });
}

So whenever I save a config file, the "change" event is received at least twice by the handler function for the same file name causing updateConfigData() to be executed multiple times. I experienced the same behavior when watching config files using C++/iNotify.

Does anyone have a clue what causes this behavior?

like image 204
Rip-Off Avatar asked Nov 05 '25 12:11

Rip-Off


1 Answers

Short Answer: It is not Node, file is really changed twice.

Long Answer

I have a very similar approach that I use for my development setup. My manager process watches all js source files if it is a development machine and restart childs on the cluster.

I had not paid any attention to this since it was just development setup; but after I read your question, I gave it a look and realized that I have the same behavior.

I edit files on my local computer and my editor updates them over sftp whenever I save. At every save, change event on the file is triggered twice.

I had checked listeners('change') for the FSWatcher object that is returned by fs.watch call; but it shows my event handler only once.

Then I did the test I should have done first: "touch file.js" on server and it triggered only once. So, for me, it was not Node; but file was really changed twice. When file is opened for writing (instead of appending), it probably triggers a change since it empties the content. Then when new content is written, it triggers the event for a second time.

This does not cause any problem for me; but if you want to prevent it, you can make an odd-even control in your event handler function by keeping the call numbers for each file and do whatever you do only on even-indexed calls.

like image 163
hasanyasin Avatar answered Nov 07 '25 10:11

hasanyasin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!