javascript - 逐一读取文件并解析

标签 javascript node.js typescript

我需要阅读的文件夹中有多个(数百个)文件。目前我正在使用一种读取所有文件然后将内容作为数组返回的方法。但我需要更改它,以便我读取一个文件并将其发送给客户端,然后我读取第二个文件,依此类推直到最后......以使其更加高效。有什么建议吗?

当前代码:

const fse = require("fs-extra");
const path = require("path");
return (
  fse
    .readdir(direc)
    .then((filenames: any) => {
      return filenames.map((filename: any) => path.join(direc, filename));
    })
    .then((filepaths: any) => {
      return filepaths.map((filepath: any) =>
        fse.readFile(filepath).then((filecontents: any) => {
          return JSON.parse(filecontents);
        })
      );
    })
    // Promise.all consumes an array of promises, and returns a
    // new promise that will resolve to an array of concrete "answers"
    .then((filecontents: any) => Promise.all(filecontents))
    .then((realcontents: any) => {
      return realcontents;
    })
);

最佳答案

不要将所有文件读取 Promise 放入一个数组中然后调用 Promise.all,而是将它们链接在一起。我对 Typescript 语法不太熟悉,所以我将提供一个纯 JS 示例代码,希望您可以转换所需的任何内容:

// ...
.then(filepaths => {
  let promise = Promise.resolve();
  filepaths.forEach(filepath => {
      promise = promise
                .then(() => fs.readFile(filePath))
                .then(handleFile)
                .catch(handleError);
  });
  return promise;
})
// ...

然后您只需要创建一个 handleFile 函数,该函数接收单个文件的文件内容并对其执行任何您想要的操作(解析它、通过响应发送回数据等) 。这样每个文件都会按顺序处理。您还希望您的 handleError 函数也返回一个已解决的 Promise,这样读取失败的文件就不会破坏整个链。

关于javascript - 逐一读取文件并解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326352/

相关文章:

javascript - 在 url 中隐藏 id 或 title 以获取 secret 信息

node.js - createReadStream 的 TypeScript 定义不接受选项中的 {start : 90, end: 99 }

javascript - 隐藏背景动画的按钮

javascript - 使用 Promises 和 xmlhttpRequests 从 github 获取公共(public)用户数据?

javascript - 共享http库

javascript - Stormpath 自定义数据

generics - TypeScript:继承类中静态方法的自引用返回类型

javascript - 如何在JS中从Y-M-D日期获取unix时间戳?

javascript - 对象未按预期呈现

node.js - Sequelize v4 |实例方法不起作用