Reading value from console, interactively

Risto Novik picture Risto Novik · Nov 14, 2011 · Viewed 192.5k times · Source

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);
    i.close();
    process.stdin.destroy();

  });

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.

Answer

rob picture rob · Nov 15, 2011

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() + "]");
  });