paulmillr / chokidar

Minimal and efficient cross-platform file watching library
https://paulmillr.com
MIT License
10.86k stars 575 forks source link

Avoid emitting 'change' when file is saved without any change #1283

Closed jsines closed 1 year ago

jsines commented 1 year ago

Describe the bug

When watching a directory for changes an event is emitted when a watched file is saved, even if there were no changes.

This was reported back in 2018 but was closed: https://github.com/paulmillr/chokidar/issues/673

This would be really helpful to fix. It's possible to work around the issue (I intend to) but I think it makes more sense being an option or the default behavior in the library itself.

The reasoning behind the original closure:

Can’t suppress the event. That’s not how these signals work.

You could hold onto before and after stats to see if the size changed (which will be imperfect, but maybe good enough), or you could read and hold onto entire file contents to compare whether any actual changes happened.

You could massively reduce the memory use of this approach by keeping a hash of the files instead. Add them all to a map when they're initialized and only emit the event if the new hash is different.

Versions (please complete the following information):

To Reproduce:

const chokidar = require('chokidar');
const watcher = chokidar.watch('.');

watcher.on('change'), () => console.log('changed!'));
// 'changed!' is logged even if the saved file was not changed
paulmillr commented 1 year ago

You could massively reduce the memory use of this approach by keeping a hash of the files instead. Add them all to a map when they're initialized and only emit the event if the new hash is different.

Calculating hash can easily take a few seconds for a large file. If you have 300,000 files, calculating hashes will continue endlessly.

We won't implement it. If you need it, you can do this by yourself, by writing a thin wrapper on top of chokidar.