2

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.

thorn0
  • 9,362
  • 3
  • 68
  • 96
Rajkamal Subramanian
  • 6,884
  • 4
  • 52
  • 69

1 Answers1

1

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.

thorn0
  • 9,362
  • 3
  • 68
  • 96
Chandu
  • 4,581
  • 2
  • 17
  • 13
  • i tried this method. This works. But i want to capture 'readable' event. – Rajkamal Subramanian Aug 18 '13 at 07:22
  • what node version are you on ? – Chandu Aug 18 '13 at 09:47
  • 1
    I went through the api docs and the event 'readable' was introduced on stream.readable from 0.9.4. make sure your node version is gte 0.9.4. Else rely on 'data' event. – Chandu Aug 18 '13 at 10:06
  • Oh you are right 'readable' event is triggered after updating to latest version. Where did you saw that information? Its not in the API doc. – Rajkamal Subramanian Aug 18 '13 at 22:32
  • Its not explicitly specified anywhere in the docs. node , kind of underwent commendable changes wrt streams from 0.8 to 0.9. I went successively through the API from 0.9 - 0.10 to see where this particular event was introduced and hit the bulls eye @0.9.4 :-) – Chandu Aug 19 '13 at 06:31