4

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?

Rip-Off
  • 358
  • 1
  • 4
  • 14
  • Could you have the chance to check the situation? Is your problem the same as mine as I explained below? Please let me know by dropping a comment if you need any clarification in my answer. – hasanyasin Jul 05 '12 at 19:30
  • Didn't my answer solve your problem? – hasanyasin Jul 09 '12 at 06:13
  • I'm sorry hasanyasin, I'm pretty busy on another project area but will definetely come back on this one. – Rip-Off Jul 09 '12 at 12:32

2 Answers2

5

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.

hasanyasin
  • 6,222
  • 1
  • 17
  • 16
0

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.

Community
  • 1
  • 1
Ryan Atallah
  • 2,977
  • 26
  • 34