【问题标题】:recursively watch a directory with node.js api使用 node.js api 递归查看目录
【发布时间】:2014-12-10 22:48:11
【问题描述】:

我正在尝试递归查看目录,但遇到了命名空间问题。

我的代码如下所示:

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 = 。我该如何解决这个问题?谢谢!

【问题讨论】:

  • 问题是 var x 不是 for 循环块的本地,并且您的回调 function 创建了一个闭包。如果您将 function{} 替换为 function (file) { return function{}; }(file),也会起作用。

标签: javascript node.js asynchronous


【解决方案1】:

您可以考虑使用:(假设 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);
      }
    }
  });
});

【讨论】:

    【解决方案2】:

    为此目的有node-watch 包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多