Skip to content

Instantly share code, notes, and snippets.

@gld1982ltd
Forked from yuanchuan/gist:2586540
Created January 29, 2016 03:33
Show Gist options
  • Save gld1982ltd/d0d7ac835011d1f9bef2 to your computer and use it in GitHub Desktop.
Save gld1982ltd/d0d7ac835011d1f9bef2 to your computer and use it in GitHub Desktop.
Watch a directory recursively
/**
* Watch a directory recursively
*
* @param {String} dir
* @param {Function} cb
*
* watchRecursive('directory', function(current) {
* console.log(current, ' changed');
* });
*/
exports.watchRecursive = (function() {
var fs = require('fs')
, path = require('path');
var lazycall = (function() {
var start = 0
, interval;
return function(fn, interval) {
interval = interval || 100;
if (+new Date() - start >= interval) {
fn && fn.call();
start = +new Date();
}
};
}());
return function watch(dir, cb) {
fs.watch(dir, function() {
lazycall(function() {
cb && cb.call(null, dir);
})
});
fs.readdir(dir, function(err, all) {
all.forEach(function(n) {
var file = path.join(dir, n);
if (fs.statSync(file).isDirectory()) {
watch(file, cb);
};
});
});
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment