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