我的应用程序需要读取包含多个文件的文件夹。所有文件都应该异步获取。所有文件的输出都应该放在一个数组中。 为了实现这一点,已经完成了以下代码。 (我用过 promise )。 对于单个文件它可以工作,但对于多个文件它不起作用。需要您的建议。
来自 files.js 的代码
function readFolder(FolderPath){
return new Promise(function(resolve, reject){
fs.readdir(FolderPath, (err, files) => {
if (err) {
logger.error(`Folder (${FolderPath}) reading Failed :` + err)
reject(error = "Reading Folder failed")
} else {
console.log('resolved')
resolve(files)
}
})
})
};
function readFile(FilePath){
return new Promise(function(resolve,reject){
fs.readFile(FilePath, (err, data) => {
if (err) {
reject(error = "Reading file failed")
} else {
console.log('Read File started :'+FilePath)
var chunk = data.toString();
var lines = chunk.split('\n');
var routes = []
for(var line = 0; line < lines.length; line++){
if (lines[line].match(/router.post/)){
currentRoute = lines[line].substring(lines[line].indexOf("'")+1 , lines[line].lastIndexOf("'"))
route = "/api/angular" + currentRoute
routes.push(route)
}
}
if (routes !== []){
console.log('routes for file is :' + routes)
}
resolve(routes)
}
})
})
};
function readFiles(FilePaths){
return new Promise(function(resolve, reject){
let routesArray = []
FilePaths.forEach(FilePath => {
console.log("File Path :"+FilePath)
readFile(FilePath)
.then((routes) => {
console.log('Concatinate')
routesArray = routesArray.concat(routes)
})
.catch((error) => {
console.log(error)
})
})
console.log(routesArray)
resolve(routesArray)
})
}
文件名:api.js(调用 promise )
const files = require('./../controlers/files')
files.readFolder(FolderPath)
.then((filesArray) => {
var FilePaths = [];
filesArray.forEach(file => {
path = "routes/"+file
FilePaths.push(path)
})
console.log(FilePaths)
return files.readFiles(FilePaths)
})
.then((routes) => {
console.log('routes :', routes)
res.status(200).send(routes)
})
.catch((error) => {
response.message = "Folder or file Reading failed";
response.success = false;
res.status(500).send(response);
})
不对的地方请指出
最佳答案
当使用带有 Promise 语法的 .forEach
时,你是“错误的”(在 readFiles
函数中)。 .forEach
是一个“回调”风格的函数,它不会像您预期的那样使用 Promise。
你需要等到所有文件都完成,我的建议是使用 Array.map
和 Promise.all
:
function readFiles(FilePaths) {
return new Promise(function (resolve, reject) {
let routesArray = []
const promises = FilePaths.map(FilePath => { // get back an array of promises
console.log("File Path :" + FilePath)
return readFile(FilePath)
.then((routes) => {
console.log('Concatinate')
routesArray.push(...routes) // I like .push function
})
.catch((error) => {
console.log(error)
})
});
Promise.all(promises)
.then(() => { // all done!
console.log(routesArray)
resolve(routesArray)
})
})
}
关于javascript - 在 node.js 中异步读取多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424336/