两次管道相同的流会产生无限循环(Piping the same stream twice creates an infinite loop)

编程入门 行业动态 更新时间:2024-10-20 15:46:51
两次管道相同的流会产生无限循环(Piping the same stream twice creates an infinite loop)

我正在练习Node.js流,我遇到以下代码问题:

'use strict' let stream = require('stream'); let logger = new stream.Transform({ transform: function (chunk, encoding, next) { console.log(`Chunk: ${chunk}`); this.push(chunk); next(); } }) let liner = new stream.Transform({ transform: function (chunk, encoding, next) { chunk.toString().split('\r\n').forEach(e=>this.push(e)); next(); } }) process.stdin.pipe(logger).pipe(liner).pipe(logger);

我期望对logger的两次调用是记录器流的不同实例,但它们似乎是相同的并且它们进入无限循环,所以我应该如何调用它们以便这段代码按预期工作。

非常感谢你。

I'm practicing with Node.js streams and I'm having problems with the following code:

'use strict' let stream = require('stream'); let logger = new stream.Transform({ transform: function (chunk, encoding, next) { console.log(`Chunk: ${chunk}`); this.push(chunk); next(); } }) let liner = new stream.Transform({ transform: function (chunk, encoding, next) { chunk.toString().split('\r\n').forEach(e=>this.push(e)); next(); } }) process.stdin.pipe(logger).pipe(liner).pipe(logger);

I expected the two calls to logger to be diferent instances of the logger stream but they seem to be the same and they get into an infinite loop, so how should I call them so this code works as intended.

Thank you very much.

最满意答案

它是相同的对象,因此预期会出现无限循环:

process.stdin.pipe(logger).pipe(liner).pipe(logger); // ^-----------------------|

尝试使用2个不同的实例:

'use strict' let stream = require('stream'); let logger = function () { return new stream.Transform({ transform: function (chunk, encoding, next) { console.log(`Chunk: ${chunk}`); this.push(chunk); next(); } }); } let liner = new stream.Transform({ transform: function (chunk, encoding, next) { chunk.toString().split('\r\n').forEach(e=> this.push(e)); next(); } }) process.stdin.pipe(logger()).pipe(liner).pipe(logger());

It's the same object so the infinite loop is expected:

process.stdin.pipe(logger).pipe(liner).pipe(logger); // ^-----------------------|

Try using 2 differents instances:

'use strict' let stream = require('stream'); let logger = function () { return new stream.Transform({ transform: function (chunk, encoding, next) { console.log(`Chunk: ${chunk}`); this.push(chunk); next(); } }); } let liner = new stream.Transform({ transform: function (chunk, encoding, next) { chunk.toString().split('\r\n').forEach(e=> this.push(e)); next(); } }) process.stdin.pipe(logger()).pipe(liner).pipe(logger());

更多推荐

本文发布于:2023-08-07 02:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   管道   Piping   stream   infinite

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!