-
-
Save gld1982ltd/d0d7ac835011d1f9bef2 to your computer and use it in GitHub Desktop.
Watch a directory recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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