I'm trying to recursively watch a directory and I'm stumbling upon a namespace issue.
My code looks like this:
for (i in files) {
var file = path.join(process.cwd(), files[i]);
fs.lstat(file, function(err, stats) {
if (err) {
throw err;
} else {
if (stats.isDirectory()) {
// Watch the directory and traverse the child file.
fs.watch(file);
recursiveWatch(file);
}
}
});
}
It appears that I'm only watching the last directory stat'd. I believe the problem is that the loop finishes before the lstat callback is finished. So every time the lstat callback's are called, file = . How do I address this? Thank you!
You might to consider using: (assuming ES5 and that files
is an Array
of filenames)
files.forEach(function(file) {
file = path.join(process.cwd(), file);
fs.lstat(file, function(err, stats) {
if (err) {
throw err;
} else {
if (stats.isDirectory()) {
// Watch the directory and traverse the child file.
fs.watch(file);
recursiveWatch(file);
}
}
});
});
There is the node-watch package for this purpose.