Risto Novik Risto Novik - 2 years ago 245
Node.js Question

Reading value from console, interactively

I thought to make an simple server http server with some console extension. I found the snippet to read from command line data.

var i = rl.createInterface(process.stdin, process.stdout, null);
i.question('Write your name: ', function(answer) {
console.log('Nice to meet you> ' + answer);


well to ask the questions repeatedly, i cant simply use the while(done) { } loop ? Also well if the server receives output at the question time, it ruins the line.

rob rob
Answer Source

you can't do a "while(done)" loop because that would require blocking on input, something node.js doesn't like to do.

Instead set up a callback to be called each time something is entered:

var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    // note:  d is an object, and when converted to a string it will
    // end with a linefeed.  so we (rather crudely) account for that  
    // with toString() and then trim() 
    console.log("you entered: [" + 
        d.toString().trim() + "]");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download