两次管道相同的流会产生无限循环(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());更多推荐
发布评论