我在node.js中遇到了這個代碼的問題。我想遞歸遍歷一個目錄樹,並將回調action
應用到樹中的每個文件。這是我的時刻代碼:使用Node.js遍歷目錄
var fs = require("fs");
// General function
var dive = function (dir, action) {
// Assert that it's a function
if (typeof action !== "function")
action = function (error, file) { };
// Read the directory
fs.readdir(dir, function (err, list) {
// Return the error if something went wrong
if (err)
return action(err);
// For every file in the list
list.forEach(function (file) {
// Full path of that file
path = dir + "/" + file;
// Get the file's stats
fs.stat(path, function (err, stat) {
console.log(stat);
// If the file is a directory
if (stat && stat.isDirectory())
// Dive into the directory
dive(path, action);
else
// Call the action
action(null, path);
});
});
});
};
的問題是,在每個循環統計經由可變path
呼籲每個文件。當回調被調用時,path
已經有另一個值,因此它dive
s到錯誤的目錄或調用action
錯誤的文件。
也許這個問題很容易通過使用fs.statSync
得到解決,但這不是我想要的解決方案,因爲它阻止了這個過程。
最後一個[npm包](http://search.npmjs.org/#/dive) – pvorb
這將通過在文件頂部放置'「use strict」;'來實現。 – Domenic
對於跨平臺兼容性,請使用節點的[path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2)函數,而不是附加原始的'「/」'。 –