0
var readline = require('readline');
var reader = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
function stdinput(){
    reader.on('line', function (cmd) {
        return cmd;
      });
}
console.log(stdinput());

output:

undefined

stdinput() function giving "undefined" before reading input from stdin. I searched many resources but not able understand why it's interpreting Asynchronously.

I am writing CLI interactive application in nodejs. it reads input many times. If we use recursion to read, it takes more stack memory and If we use callbacks, Promise and Async/await here also getting undefined before stdinput() i.e below part of the code is executing first before reading input.

2 Answers2

1

Or you can use a callback:

var readline = require('readline');
var reader = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

function stdinput(callback){
    reader.on('line', function (cmd) {
        callback (cmd);
      }); 
}

stdinput(function (cmd) {
    console.log('cmd: ', cmd); 
});
Ari Singh
  • 1,228
  • 7
  • 12
0

It's because the function stdinput is returning before the reader.on ('line',.. event happens. Try this approach:

var readline = require('readline');
var reader = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: true
});


function stdinput(){
    return new Promise((resolve) => {
        reader.on('line', function (cmd) {
            resolve(cmd);
        });
    });
}

stdinput().then((cmd) => console.log("cmd: ", cmd))

And you could try this approach too:

function processInput(cmd) {
    // Do something cool with the cmd
    //
    //
    console.log('processInput: command: %s processed', cmd);
}

function stdinput(){
    reader.on('line', function (cmd) {
        console.log('cmd: ', cmd);
        processInput(cmd);
    });
}

Or this:

var askForName = () => console.log("What's your name? ");
function sayHello(){
    askForName();
    reader.on('line', function (name) {
        console.log('Hello ' + name + "!");
        askForName();
    });
}

sayHello();

And to make it clear, the original stdInput effectively returned undefined, since it exited without setting a return value, this is why you were getting this result logged to the console.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40