paulmillr/chokidar — pull request #145 by joeyespo (2014-08-22 19:28:06+00:00)
Title: Fix #144 by throttling the event handler

So turns out, the multiple "change" events problem when using `fs.watch` is actually a [known issue with Node](https://github.com/joyent/node/issues/2126). Ubuntu and OSX are [also affected](https://github.com/joyent/node/issues/2126#issuecomment-6027708).

Here's [a comment](https://github.com/joyent/node/issues/2126#issuecomment-6633415) from the Node issue:

> This is expected. The file is first truncated when it is opened, and then data is written. This triggers 2 change events. We cannot and won't do anything to prevent that.

And [a suggested](https://github.com/joyent/node/issues/2126#issuecomment-22615233) on how to fix Node from the same thread. It suggests differentiating the "change" event by adding an "open" event. It's a year old though with no response, so unfortunately, looks like the fix will have to be at a higher level.

This fixes the problem by throttling the changed event. It uses `setTimeout(f, 0)`, which lets the other queued messages be processed first, then executes immediately after. This is enough to prevent the second event--which is posted immediately after the first--to be filtered out. All without affecting the handler, and without a noticeable delay (because the handler gets called immediately after the second message, which is the *actual* write message).

I tested it on Windows. It should work for other OS's, but if they do happen to post their open / write messages with any delay, the `setTimeout` parameter here can be non-zero (preferably when `isWindows === false` so it doesn't affect Windows users).