Search code examples
node.jsnode-streams

NodeJs Readable Error When Reading From Stream


I want to print the output every 1 second but i get the below error. I thought that read method is called synchronously but it seems that is not the case. Can someone explain how the read method executes and why i get this error?

const {Readable} = require('stream');

var out = new Readable({

    read(size){
        console.log('read');

        setTimeout(()=>{


        console.log(this.k);

        console.log('before push');

        this.push(String.fromCharCode(this.k++)+'\n');

        console.log('after push\n');
        if(this.k>65){
            this.push(null);
            console.log('null\n');
        }

    },1000);


    }

});
out.k = 65;
out.pipe(process.stdout);

And i get this error:

events.js:183
      throw er; // Unhandled 'error' event
      ^
    Error: stream.push() after EOF
        at readableAddChunk (_stream_readable.js:240:30)
        at Readable.push (_stream_readable.js:208:10)
        at Timeout.setTimeout [as _onTimeout] (C:\Users\x90540\Node\index.js:106:14)
        at ontimeout (timers.js:475:11)
        at tryOnTimeout (timers.js:310:5)
        at Timer.listOnTimeout (timers.js:270:5)

Solution

  • For anyone who comes to read this later on:

    This behavior would not reproduce if you use the updated version of Node. A detailed discussion of this can be found here:

    https://github.com/nodejs/node/issues/3203#issuecomment-355137794