NodeJS Filesystem Watch throwing event twice or more often

此生再无相见时 提交于 2019-12-06 02:16:53

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.

Ryan Atallah

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!