У меня проблема с этим кодом в node.js. Я хочу рекурсивно пройти через дерево каталогов и применить обратный вызов action
к каждому файлу в дереве. Это мой код на данный момент:
var fs = require("fs");
// General function
var dive = function (dir, action) {
// Assert that it 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 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);
});
});
});
};
Проблема заключается в том, что в каждом цикле stat вызывается для каждого файла через переменную path
. Когда вызывается обратный вызов, path
уже имеет другое значение и поэтому он dive
попадает в неправильные каталоги или вызывает action
для неправильных файлов.
Вероятно, эта проблема может быть легко решена с помощью fs.statSync
, но это не то решение, которое я бы предпочел, поскольку он блокирует процесс.