【发布时间】:2011-10-25 21:06:02
【问题描述】:
我在 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 调用统计信息。当回调被调用时,path 已经有另一个值,因此它 dives 进入错误的目录或调用 action 以获得错误的文件。
使用fs.statSync 可能很容易解决这个问题,但这不是我想要的解决方案,因为它会阻塞进程。
【问题讨论】:
标签: javascript node.js filesystems