我正在尝试递归地监视目录,但偶然发现了命名空间问题。
我的代码如下所示:
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);
}
}
});
}
看来我只查看最后一个目录。我认为问题在于循环在 lstat 回调完成之前完成。因此,每次调用 lstat 回调时, file = .我该如何解决这个问题?谢谢!
最佳答案
您可能会考虑使用:(假设 ES5 并且 files
是文件名的 Array
)
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);
}
}
});
});
关于javascript - 使用 node.js api 递归地监视目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360444/