Ryan Callahan
Ryan Callahan

Reputation: 115

Trying to read input from console with readline in node.js, but the application isn't waiting for input

I'm trying to read in a word from the console to use in a hangman-like application. So far the prompt of "enter your word" is showing up, but the application won't wait for input to continue.

I've set VS code to use an external console, tried using different methods without readline, and watched a few videos to try and get this to work.

var readline = require('readline');

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

function getWord(){

    var word = "";

    rl.question("Enter your word", function(answer){
        word = answer
    })

    var wordArray = word.split('');

    return wordArray;
}

console.log(getWord());

I would expect it to wait for input then continue but it doesn't.

Upvotes: 0

Views: 941

Answers (1)

Matteo Basso
Matteo Basso

Reputation: 2704

rl.question performs an async operation, so you cannot be sure that word is equals to answer when you try to .split. However, you are sure that user has typed something into the callback that receives answer as parameter.

In other words, you have to change your code to handle this situation, you might consider the usage of a Promise:

var readline = require('readline');

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

const getWord = () => {
  return new Promise(resolve => {
    rl.question("Enter your word", function(answer) {
        resolve(answer.split(''));
    });
  });
}

getWord().then(array => {
  console.log(array);
  process.exit(0);
});

Upvotes: 2

Related Questions