[英]Using async/await syntax with node stream
我在 ubuntu 上使用节点 18.7。 我正在尝试将一堆 csv 文件解析为对象(使用 csv-parse),最终加载到数据库中。 因为有大量的这些我决定尝试流,我想使用异步等待风格。
到目前为止,我有:
const { parse } = require('csv-parse');
const path = __dirname + '/file1.csv';
const opt = { columns: true, relax_column_count: true, skip_empty_lines: true, skip_records_with_error: true };
console.log(path);
const { pipeline } = require('stream');
// const pipeline = stream.pipeline;
async function readByLine(path, opt) {
const readFileStream = fs.createReadStream(path);
var csvParser = parse(opt, function (err, records) {
if (err) throw err;
});
await pipeline(readFileStream, csvParser, (err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
});
for await (const record of csvParser) {
console.log(record);
}
}
readByLine(path, opt)
当我运行它时,我看到:
Pipeline succeeded.
但是解析的对象不会发送到控制台。 我究竟做错了什么?
编辑1:
我将代码更改为:
async function readByLine(path, opt) {
const readFileStream = fs.createReadStream(path);
var csvParser = parse(opt, function (err, records) {
if (err) throw err;
});
await pipeline(readFileStream, csvParser, (err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
});
// for await (const record of csvParser) {
// console.log(record);
// }
return csvParser;
}
(async function () {
const o = await readByLine(path, opt);
console.log(o);
})();
结果是一个具有一百万个属性的 object,但有些属性看起来像屏幕截图中的那样。
您只能await
promise 有用。
您正在使用的pipeline
function 不会返回 promise。
如果您查看文档,您将看到:
管道 API 提供了 promise 版本,它还可以接收选项参数作为带有信号
<AbortSignal>
属性的最后一个参数。 当信号中止时,将在底层管道上调用destroy,并带有AbortError。const { pipeline } = require('node:stream/promises'); const fs = require('node:fs'); const zlib = require('node:zlib'); async function run() { await pipeline( fs.createReadStream('archive.tar'), zlib.createGzip(), fs.createWriteStream('archive.tar.gz') ); console.log('Pipeline succeeded.'); } run().catch(console.error);
注意传递给require
的不同值。 请改用该版本的pipeline
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.