【问题标题】:Node JS: How to catch the individual errors while reading files, in case multiple files are read on Promise.all?Node JS:如何在读取文件时捕获单个错误,以防在 Promise.all 上读取多个文件?
【发布时间】:2021-07-19 17:11:24
【问题描述】:

我有 10 个不同的文件,我需要读取它们的内容并将其合并到一个对象中(在 NodeJS 中)。我用下面的代码成功地做到了:

const fs = require('fs');
const path = require('path');
const { promisify } = require("util");    
const readFileAsync = promisify(fs.readFile);

let filePathArray = ['path/to/file/one', ... , 'path/to/file/ten'];
Promise.all(
  filePathArray.map(filePath => {          
    return readFileAsync(filePath);
  })
).then(responses => { //array of 10 reponses
  let combinedFileContent = {};
    responses.forEach((itemFileContent, index) => {
      let tempContent = JSON.parse(itemFileContent);
      //merge tempContent into combinedFileContent 
    }
});

但我想知道的是,如果在尝试读取文件时出现错误,如何发现?读取单个文件时,其工作原理如下:

fs.readFile(singleFilePath, (singleFileErr, singleFileContent) => {
  if (singleFileErr) {
    //do something on error, while trying to read the file        
  }
});

所以我的问题是,如何从第二个代码 sn-p 访问错误 inn 第一个代码 sn-p,它对应于 singleFileErr? 我面临的问题是:如果某些文件不存在,我想检查错误并跳过此文件,但由于我无法检测到当前实现的错误,我的整个块崩溃并且我无法因为这个而合并其他9个文件。我想使用我在第二个 sn-p 中提到的错误检查。

【问题讨论】:

    标签: node.js fs readfile


    【解决方案1】:

    查看Promise.allSettled 函数,它将运行每个传递给它的Promise,并在最后告诉您哪些成功,哪些失败。

    【讨论】:

      【解决方案2】:

      不妨试试这样的:

      • map() 回调中,如果找不到文件,则返回一个解析为null 的承诺。
      • 在 Promise 链中引入一个中间阶段,过滤掉 null 响应。

      这看起来像这样:

      Promise.all(
        filePathArray.map(filePath => {          
          return readFileAsync(filePath).catch(function(error){
            if(isErrorFileDoesNotExist(error)) return null
            throw error;
          })
        });
      ).then(responses => {
         return responses.filter(response => response != null) 
      })
      .then(filteredResponses => { 
        // .. do something
      });
      

      这对你有用吗?请注意,这假设您实际上能够区分丢失的文件错误和readFileAsync() 返回的承诺可能拒绝的其他错误 - 大概是通过此 sn-p 中的 isErrorFileDoesNotExist() 函数。

      【讨论】:

        猜你喜欢
        • 2018-07-12
        • 2022-11-03
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 1970-01-01
        • 2020-02-13
        • 2015-09-17
        • 1970-01-01
        相关资源
        最近更新 更多