Hidden
Hidden

Reputation: 4305

Piping the same stream twice creates an infinite loop

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.

Upvotes: 1

Views: 931

Answers (1)

Shanoor
Shanoor

Reputation: 13672

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

Upvotes: 4

Related Questions