Search code examples
node.jsnode.js-stream

nodejs stdin readable event not triggered


The readable event is not triggered in the process.stdin

test.js

var self = process.stdin, data ;

self.on('readable', function() {
    var chunk = this.read();
    if (chunk === null) {
        handleArguments();
    } else {
       data += chunk;
    }
});

self.on('end', function() {
   console.log("end event",data )
});

Then when i do node test.jsand start typing the in the console, the readable event is not triggered at all.

Please tell me how to attach readable listener to process.stdin stream.


Solution

  • If you are trying to capture what you type on to console, try these steps,

    process.stdin.resume();
    

    process.stdin starts in paused state.You need to bring it to ready state. listen on 'data' event to capture the data typed in console.

    process.stdin.on('data', function(data) {       
        console.log(data.toString());    
    }); 
    

    I am not sure if this helped your actual problem.Hope atleast it gives you some insight.

    Additional Info:

    The readable event is introduced in Node.js v0.9.4. So check if the node you are using is gte 0.9.4.

    Note from node api docs:

    The 'data' event emits either a Buffer (by default) or a string if setEncoding() was used.

    Note that adding a 'data' event listener will switch the Readable stream into "old mode", where data is emitted as soon as it is available, rather than waiting for you to call read() to consume it.