gpt4 book ai didi

javascript - 使用 node.js api 递归地观察一个目录

转载 作者:行者123 更新时间:2023-11-30 18:27:55 25 4
gpt4 key购买 nike

我试图递归地观察一个目录,但我遇到了命名空间问题。

我的代码是这样的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com