Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to readline infinitely in Node.js

while(1){
    rl.question("Command: ",function(answer){
    console.log(answer);
    })
}

Just tried this code, but instead get input one by one, it blink the "Command: " line. I know node.js is non-blocking but i don't know how to fix this problems.

like image 347
user2477 Avatar asked Jun 28 '14 06:06

user2477


People also ask

How do I read the last 10 lines of a node js file?

createReadStream('your/file'); var outstream = new stream; var rl = readline. createInterface(instream, outstream); rl. on('line', function(line) { // process line here }); rl. on('close', function() { // do something on finish here });

How do I read the next line in node JS?

Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');

What is createInterface in node JS?

The method createInterface() takes two parameters – the input stream and output stream – to create a readline interface. The third parameter is used for autocompletion and is mostly initialized as NULL .


2 Answers

var readline = require('readline');
var log = console.log;

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var recursiveAsyncReadLine = function () {
  rl.question('Command: ', function (answer) {
    if (answer == 'exit') //we need some base case, for recursion
      return rl.close(); //closing RL and returning from function.
    log('Got it! Your answer was: "', answer, '"');
    recursiveAsyncReadLine(); //Calling this function again to ask new question
  });
};

recursiveAsyncReadLine(); //we have to actually start our recursion somehow

The key is to not to use synchronous loops. We should ask next rl.question only after handling answer. Recursion is the way to go. We define function that asks the question and handles the answer and then call it from inside itself after answer handling. This way we starting all over, just like with regular loop. But loops don't care about ansyc code, while our implementation cares.

like image 120
mynameisdaniil Avatar answered Oct 08 '22 11:10

mynameisdaniil


Another option, via the Node.js documentation, is to use events:

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('OHAI> ');
rl.prompt();

rl.on('line', function(line) {
    switch(line.trim()) {
        case 'hello':
            console.log('world!');
            break;
        default:
            console.log('Say what? I might have heard `' + line.trim() + '`');
        break;
    }
    rl.prompt();
}).on('close', function() {
    console.log('Have a great day!');
    process.exit(0);
});
like image 30
nwayve Avatar answered Oct 08 '22 11:10

nwayve