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