My application requires to read a folder having multiple files. All files should be fetched asynchronously. Output from all files should be clubbed in a single array. In order to achieve this, below code has been done. (I have used promise). For single file it is working, but for multiple files it is not working. Need your suggestions.
code from 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)
})
}
file name: api.js (Call to 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);
})
Please suggestion where I am wrong.
readFilesyou either deal with one Promise at a time, or use Promise.all to wait for multiple Promises at once - neither of which you are doing - Also, I doubt the code you posted works even for a single file since youresolve(routesArray)before it could even have had anything added to it