NodeJs through处理流
through2主要是基于streams2
(2指的是API稳定性)封装的transform stream
。其内部仅是封装了Transform的构造函数,以及更为易用的objectMode
模式。
through2
并未引用node默认提供的stream模块,而是使用社区中较为流行的readable-stream
模块,主要是为了对之前node版本做了兼容支持。
我们可以先看一段关于transform stream使用的基本示例:
1 2 3 4 5 6 7 8 9 10 11 | const { Transform } = require( 'stream' ); const upperCaseTr = new Transform({ transform(chunk, encoding, callback) { // 转换为大写、push到可读流 this .push(chunk.toString().toUpperCase()); callback(); } }); process.stdin.pipe(upperCaseTr).pipe(process.stdout); |
对应的如果换成through2
写法。
1 2 3 4 | process.stdin.pipe(through2( function (chunk, enc, callback) { this .push(chunk.toString().toUpperCase()) callback() })).pipe(process.stdout); |
接下来我们再看看对象模式,默认地,stream除了接收 Buffer/String 值。还有一个对象模式(objectMode
)的标识,我们可以设置以接受任意Javascript 对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | const { Transform } = require( 'stream' ); const commaSplitter = new Transform({ readableObjectMode: true , transform(chunk, encoding, callback) { this .push(chunk.toString().trim().split( ',' )); callback(); } }); const arrayToObject = new Transform({ readableObjectMode: true , writableObjectMode: true , transform(chunk, encoding, callback) { const obj = {}; for ( let i=0; i < chunk.length; i+=2) { obj[chunk[i]] = chunk[i+1]; } this .push(obj); callback(); } }); const objectToString = new Transform({ writableObjectMode: true , transform(chunk, encoding, callback) { this .push(JSON.stringify(chunk) + '\n' ); callback(); } }); process.stdin .pipe(commaSplitter) .pipe(arrayToObject) .pipe(objectToString) .pipe(process.stdout) |
我们在终端输入:
1 2 | $ a,b,c,d $ { "a" : "b" , "c" : "d" } |
对应的如果换成through2
写法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | process.stdin .pipe(through2.obj( function (chunk, enc, callback) { this .push(chunk.toString().trim().split( ',' )); callback(); })) .pipe(through2.obj( function (chunk, enc, callback) { const obj = {}; for ( let i=0; i < chunk.length; i+=2) { obj[chunk[i]] = chunk[i+1]; } this .push(obj); callback(); })) .pipe(through2.obj( function (chunk, enc, callback) { this .push(JSON.stringify(chunk) + '\n' ); callback(); })) .pipe(process.stdout) |
pipe中间进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 | var through2 = require( 'through2' ); var stream = through2(write,end) process.stdin .pipe(stream) .pipe(process.stdout); function write(line,_,next){ this .push(line.toString().toUpperCase()) next(); }) function end(done){ done(); }) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!