fs.watch fired twice when I change the watched file fs.watch fired twice when I change the watched file node.js node.js

fs.watch fired twice when I change the watched file


The fs.watch api:

  1. is unstable
  2. has known "behaviour" with regards repeated notifications. Specifically, the windows case being a result of windows design, where a single file modification can be multiple calls to the windows API


I make allowance for this by doing the following:

var fsTimeoutfs.watch('file.js', function(e) {    if (!fsTimeout) {        console.log('file.js %s event', e)        fsTimeout = setTimeout(function() { fsTimeout=null }, 5000) // give 5 seconds for multiple events    }}


I suggest to work with chokidar (https://github.com/paulmillr/chokidar) which is much better than fs.watch:

Commenting its README.md:

Node.js fs.watch:

  • Doesn't report filenames on OS X.
  • Doesn't report events at all when using editors like Sublime on OS X.
  • Often reports events twice.
  • Emits most changes as rename.
  • Has a lot of other issues
  • Does not provide an easy way to recursively watch file trees.

Node.js fs.watchFile:

  • Almost as bad at event handling.
  • Also does not provide any recursive watching.
  • Results in high CPU utilization.