gpt4 book ai didi

node.js - 通过管道传输同一流两次会产生无限循环

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:03 25 4
gpt4 key购买 nike

我正在练习 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);

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

非常感谢。

最佳答案

这是同一个对象,因此预计会出现无限循环:

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());

关于node.js - 通过管道传输同一流两次会产生无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35382286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com