fs.watch fired twice when I change the watched file
The fs.watch
api:
- is unstable
- 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
If you need to watch your file for changes then you can check out my small library on-file-change. It checks file sha1 hash between fired change
events.
Explanation of why we have multiple fired events:
You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up.
Source
I make allowance for this by doing the following:
var fsTimeout
fs.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.