两次管道传输相同的流会创建一个无限循环
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);
我原以为对记录器的两次调用是记录器流的不同实例,但它们看起来是一样的,而且它们进入了无限循环,所以我应该如何调用它们才能使这段代码按预期工作。
非常感谢。
这是同一个对象,因此预期会出现无限循环:
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 流,但我在使用以下代码时遇到问题:
'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());