Ответ 1
var path = dir + "/" + file;
Вы забыли сделать path
локальную переменную. Теперь он не будет изменен за спиной в цикле.
У меня проблема с этим кодом в 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
, но это не то решение, которое я бы предпочел, поскольку он блокирует процесс.
var path = dir + "/" + file;
Вы забыли сделать path
локальную переменную. Теперь он не будет изменен за спиной в цикле.
Используйте node-dir для этого. Поскольку для каталогов и файлов требуется отдельное действие, я дам вам 2 простых итератора с помощью node -dir.
Асинхронно итерации файлов каталога и его подкаталогов и передачи массива путей к обратному вызову.
var dir = require('node-dir');
dir.files(__dirname, function(err, files) {
if (err) throw err;
console.log(files);
//we have an array of files now, so now we'll iterate that array
files.forEach(function(filepath) {
actionOnFile(null, filepath);
})
});
Асинхронно перебирать подкаталоги каталога и его подкаталогов и передавать массив путей каталога к обратному вызову.
var dir = require('node-dir');
dir.subdirs(__dirname, function(err, subdirs) {
if (err) throw err;
console.log(subdirs);
//we have an array of subdirs now, so now we'll iterate that array
subdirs.forEach(function(filepath) {
actionOnDir(null, filepath);
})
});
Не уверен, что если я действительно опубликую это как ответ, но для вашего удобства и других пользователей, это переписанная версия OP, которая может оказаться полезной. Он обеспечивает:
Код:
/**
* dir: path to the directory to explore
* action(file, stat): called on each file or until an error occurs. file: path to the file. stat: stat of the file (retrived by fs.stat)
* done(err): called one time when the process is complete. err is undifined is everything was ok. the error that stopped the process otherwise
*/
var walk = function(dir, action, done) {
// this flag will indicate if an error occured (in this case we don't want to go on walking the tree)
var dead = false;
// this flag will store the number of pending async operations
var pending = 0;
var fail = function(err) {
if(!dead) {
dead = true;
done(err);
}
};
var checkSuccess = function() {
if(!dead && pending == 0) {
done();
}
};
var performAction = function(file, stat) {
if(!dead) {
try {
action(file, stat);
}
catch(error) {
fail(error);
}
}
};
// this function will recursively explore one directory in the context defined by the variables above
var dive = function(dir) {
pending++; // async operation starting after this line
fs.readdir(dir, function(err, list) {
if(!dead) { // if we are already dead, we don't do anything
if (err) {
fail(err); // if an error occured, let fail
}
else { // iterate over the files
list.forEach(function(file) {
if(!dead) { // if we are already dead, we don't do anything
var path = dir + "/" + file;
pending++; // async operation starting after this line
fs.stat(path, function(err, stat) {
if(!dead) { // if we are already dead, we don't do anything
if (err) {
fail(err); // if an error occured, let fail
}
else {
if (stat && stat.isDirectory()) {
dive(path); // it a directory, let explore recursively
}
else {
performAction(path, stat); // it not a directory, just perform the action
}
pending--; checkSuccess(); // async operation complete
}
}
});
}
});
pending--; checkSuccess(); // async operation complete
}
}
});
};
// start exploration
dive(dir);
};
Другая подходящая библиотека - filehound. Он поддерживает фильтрацию файлов (если требуется), обратные вызовы и promises.
Например:
const Filehound = require('filehound');
function action(file) {
console.log(`process ${file}`)
}
Filehound.create()
.find((err, files) => {
if (err) {
return console.error(`error: ${err}`);
}
files.forEach(action);
});
Библиотека хорошо документирована и содержит многочисленные примеры распространенных случаев использования. https://github.com/nspragg/filehound
Отказ от ответственности: Я автор.
Не заново изобретайте колесо - используйте и не используйте вместо него открытый источник. Выполните одно из следующих действий:
function loop( ) {
var item = list.shift( );
if ( item ) {
// content of the loop
functionWithCallback( loop );
} else {
// after the loop has ended
whatever( );
}
}