2012-04-28 20 views
1

我试图递归观察一个目录,并且我在命名空间问题上磕磕绊绊。用node.js api递归观察一个目录

我的代码如下所示:

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); 
      } 
     } 
    }); 
} 

看来,我只能眼睁睁地看着最后一个目录stat'd。我相信问题是循环在lstat回调完成之前完成。所以每次调用lstat回调时,file =。我如何解决这个问题?谢谢!

+0

问题是'var x'对于for循环块来说不是本地的,你的回调函数''会创建一个闭包。如果你用'function(file){return function {}替换了'function {}',那么也可以工作。 }(文件)'。 – 2014-07-01 19:42:28

回答

2

你可能考虑使用:(假设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); 
     } 
    } 
    }); 
}); 
+0

这对我有用。谢谢! – 2012-04-28 04:37:22