2012-04-28 19 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