javascript - 在 node.js 中异步读取多个文件

标签 javascript node.js promise es6-promise

我的应用程序需要读取包含多个文件的文件夹。所有文件都应该异步获取。所有文件的输出都应该放在一个数组中。 为了实现这一点,已经完成了以下代码。 (我用过 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.mapPromise.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/

相关文章:

node.js - NodeJS 错误 : Module version mismatch. 预期 48,得到 46

node.js - 如何访问cheerio 中的表格元素?

javascript - 找不到变量 : Promise on iOS 7

javascript - 具有异步初始化的单例

javascript - Linq.js 子查询

javascript - React Infinite Scroll 超出最大更新深度

Javascript/jQuery : How to detect img is fully downloaded or not?

javascript - IE8 不在列表中使用 JQUERY 显示 JSON 数据

javascript - RxJS 5 子类化 Observable - 静态方法返回父类的实例

javascript - React axios - 尽管使用箭头函数但仍丢失此上下文