我对node.js中的这段代码有一个问题。我想递归地遍历目录树,并将回调action
应用于树中的每个文件。这是我目前的代码:
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);
});
});
});
};
问题是,在for each循环中,通过变量path
为每个文件调用stat。当回调被调用时,path
已经有了另一个值,因此它将dive
%s放到错误的目录中,或者为错误的文件调用action
。
也许这个问题可以通过使用fs.statSync
很容易地解决,但这不是我喜欢的解决方案,因为它阻塞了进程。
https://stackoverflow.com/questions/7041638
复制相似问题