如何在 node.js 中组合转换流 [英] How to compose transform Streams in node.js

查看:44
本文介绍了如何在 node.js 中组合转换流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作为一系列转换流实现的 csv 解析器:

I have a csv parser implemented as a series of transform streams:

process.stdin
    .pipe(iconv.decodeStream('win1252'))
    .pipe(csv.parse())
    .pipe(buildObject())
    .pipe(process.stdout);

我想抽象解析器(在它自己的模块中)并且能够做到:

I'd like to abstract the parser (in its own module) and be able to do:

process.stdin.
    .pipe(parser)
    .pipe(process.stdout);

其中 parser 只是之前使用的转换流的组合.

where parser is just the composition of the previously used transform streams.

如果我这样做

var parser = iconv.decodeStream('win1252')
    .pipe(csv.parse())
    .pipe(buildObject());

然后 parser 被设置为 buildObject() 流,只有这个转换流接收数据.

then parser is set to the buildObject() stream and only this transformation stream receives the data.

如果我这样做

var parser = iconv.decodeStream('win1252');
parser
    .pipe(csv.parse())
    .pipe(buildObject());

它也不起作用,因为 .pipe(process.stdout) 将在第一个转换流上被调用,而另外两个将被绕过.

it doesn't work either, as .pipe(process.stdout) will be called on the 1st transform stream and the 2 others will be bypassed.

对于流的优雅组合有什么建议吗?

Any recommendation for an elegant composition of streams?

推荐答案

不幸的是,没有内置的方法可以做到这一点,但是有很酷的 多管道 包.像这样使用:

Unfortunately, there is no built-in way to do that, but there is cool multipipe package. Use like this:

var multipipe = require('multipipe');

var parser = multipipe(iconv.decodeStream('win1252'), csv.parse(), buildObject());

这篇关于如何在 node.js 中组合转换流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆