node-watch
A neat fs.watch wrapper.
![NPM](https://nodei.co/npm/node-watch.png?downloads=true&downloadRank=true&stars=true)
Installation
npm install node-watch
Example
var watch = require('node-watch');
watch('somedir_or_somefile', { recursive: true }, function(evt, name) {
console.log(name, ' changed.');
});
This is a completely rewritten version, much faster and in a more memory-efficient way.
So with recent nodejs versions under OS X or Windows you can do something like this:
watch('/', { recursive: true }, console.log);
Why
- Some editors will generate temporary files which will cause the callback function to be triggered multiple times.
- When watching a single file the callback function will only be triggered once.
Missing an option to watch a directory recursively.- Recursive watch is not supported on Linux or in older versions of nodejs.
Notice
- The
recursive
option is defaults to be false
since v0.5.0. - Parameters in the callback function always provide event name since v0.5.0.
Events
The events provided by the callback function would be either update
or remove
.
watch('./', function(evt, name) {
if (evt == 'remove') {
}
if (evt == 'update') {
}
});
Watcher object
watch
function returns a fs.FSWatcher like object as the same as fs.watch
.
var watcher = watch('./', { recursive: true });
watcher.on('change', function(evt, name) {
});
watcher.on('error', function(err) {
});
watcher.close();
filter
: Filter files or directories or skip to watch them.
var options = {
recursive: true,
filter : function(name) {
return !/node_modules/.test(name);
}
};
watch('mydir', options, console.log);
Other ways to filter
a) filtering directly inside the callback function:
watch('./', { recursive: true }, function(evt, name) {
if (!/node_modules/.test(name)) {
}
});
b) filtering with higher order function:
function filter(pattern, fn) {
return function(evt, name) {
if (pattern.test(name)) {
fn(evt, name);
}
}
}
watch('.', filter(/\.js$/, console.log));
Misc
1. Watch mutiple files or directories in one place
watch(['file1', 'file2'], console.log);
2. Catch errors after deleting a watched directory on Windows
watch('somedir', console.log)
.on('error', function() {
});