如何将Node.js事件回调函数流转换为异步迭代器
Mar 3, 2024 2024年3月3日
Here’s an interesting Node.js exercise: 下面是一个有趣的Node.js练习:
Let’s say you’re streaming something (eg. reading a file in memory), but the only API you have available to you is a series of event handler callbacks. 让我们假设你正在流的东西(例如。阅读内存中的文件),但您唯一可用的API是一系列事件处理程序回调。
For example the stream API of the csv-parse
library has an API like the following (ignore the fact that the library also has an Async Iterator API for now):
例如,csv-parse
库的stream API具有如下所示的API(忽略该库现在也具有Async Iterator API的事实):
import { parse } from 'csv-parse';
const parser = parse({ delimiter: ',' });
parser.on('readable', () => {
let record;
while ((record = parser.read()) !== null) {
console.log(record);
}
});
parser.on('error', (err) => console.error(err.message));
parser.on('end', () => {});
This is a bit ugly though. 不过,这有点难看。
How can one turn the above code into a simple for await
loop?
如何将上面的代码变成一个简单的forawait
循环?
for await (const record of asyncIterable) {
console.log(record);
}