【发布时间】:2020-04-23 10:14:56
【问题描述】:
我正在尝试使用 nodejs readline 逐行读取文件,对于每一行我想异步执行一些功能,然后继续直到文件末尾。
const readline = require("readline");
const fs = require("fs");
let rl = readline.createInterface({
input: fs.createReadStream('b'),
crlfDelay: Infinity
});
rl.on('line', async (line) => {
console.log('start line');
await both();
console.log('end line');
});
rl.on('close', () => {
console.log('read complete');
});
function one() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 2000);
});
}
function two() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 3000);
});
}
async function both() {
ap = [];
ap.push(one());
ap.push(two());
console.log('processing line');
await Promise.all(ap);
console.log('line processed');
}
文件b 可以是任何包含一些行的文件,例如,
1
2
3
4
5
6
7
我期待的输出如下:
起跑线
线加工
生产线
终点线
.
.
.
但是,我无法维持秩序。
据我了解,'line' 事件似乎正在发出,它一次又一次地调用回调!。
有什么方法可以让这个事件等到手头的事件被异步处理(异步运行的各个步骤),然后重复。
**重要更新** 因此,用例的文件将包含大约 >5GB 的 CSV 文本。 我们有一个
【问题讨论】:
-
line 事件不会等待之前任何 line 事件中的异步代码 - 你需要创建某种队列 - 我想知道异步生成器是否适合
标签: javascript node.js async-await dom-events readline