-1
我想從一個特定的目錄中讀取所有(文本)文件,它是遞歸的所有子目錄。我能夠讀取文件並將結果附加到全局變量。但我想在所有操作結束時訪問變量。我正在嘗試承諾,但我無法訪問它。請幫助 節點js具有遞歸功能的承諾
var file_path = `C:\\Users\\HP\\Desktop\\test_folder`;
const fs = require('fs');
var final_array = [];
let getFolderTree = function(file_path) {
return new Promise(function(resolve, reject) {
fs.readdir(file_path, function(err, folders) {
if (err) {
console.log("error reading folder :: " + err);
} else {
if (folders.length !== 0) {
for (let i = 0; i < folders.length; i++) {
if (folders[i].endsWith("txt")) {
let text_file_path = file_path + `\\` + folders[i];
fs.readFile(text_file_path, function(error_read, data) {
if (error_read) {
console.log("error reading " + error_read);
} else {
return resolve(final_array.push(data));// want to access final_array at the end of all operations
}
});
} else {
let current_path = file_path + `\\` + folders[i];
getFolderTree(current_path);
}
}
}
}
});
});
}
getFolderTree(file_path).then(function() {
console.log(final_array); // this is not working
});
如果我理解你的問題是什麼,你要添加'then'和'catch'到你的遞歸調用:'getFolderTree(current_path).then(/ * do something * /)。catch(/ * handle error * /);'另外,如果我正確地讀你的代碼, '循環不會做你想做的事。而且你會希望確保你的承諾在任何情況下都能解決/拒絕。 –