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?
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.
See my response to a similar question which explains that the problem is being caused by your editor making multiple edits to the file on save.