0

I'm trying to get user input, save it to a variable and do other stuff with it, but the readline function is not working the way I'm intending.

here is my code:

var readline = require('readline')

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

var response
rl.question("Enter a number ", function (answer) {
    response = answer
    rl.close();
});

console.log('The user entered: ', response)
Undool Sipper
  • 35
  • 1
  • 1
  • 6

2 Answers2

7
var readline = require('readline')

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

var response
rl.question("Enter a number ", function (answer) {
    response = answer
    outside();
    rl.close();
});

outside = function(){
    console.log('The user entered: ', response)
}

The console.log ran before the user entered anything into the standard input.

The nature of asynchronous nodeJS can be tricky to get the head around at times. Try the code above should do the trick.

3

The code in the callback only runs when the user has actually typed a line. Your console.log() will not wait for that to happen. The interface is asynchronous.

Move the console.log() call inside the callback, and you'll see that it works.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • hmmm, but then how would I use the "response" variable later on in my code (outside the callback block)? – Undool Sipper Jun 19 '17 at 14:58
  • 1
    @UndoolSipper you don't. Structure your code such that the work you need to do with the lines of text is callable as a function, and invoke that function from the `.question()` callback function. That's the general nature of asynchronous programming in JavaScript. – Pointy Jun 19 '17 at 14:59