简体   繁体   中英

How can I use prompt-sync to get the value of 1 keypress?

I am trying to write a command line game in JS that takes user input. I am using prompt-sync module to get user input in node, but I am having trouble figuring out how to limit the user input to one keypress. The code below gives you an idea of the functionality I'm trying to implement:

const prompt = require("prompt-sync")();
let playAgain = prompt(`Play again? Enter y to replay, any other character to exit: `);
if (playAgain.toUpperCase === 'Y') {
  runGame();
} else {
  return false;
} 

I have read the documentation but am relatively new to node and can't find anything that indicates how to end the input before the 'Enter' button is hit. Is there a way to do this? Should I use a different module like Inquirer.js?

You're in the right direction. The function prompt returns a string which represents the keyboard's key that was pressed.

In order to check if the user's answer was a capital "Y" you'd have to compare playAgain (which is a string with the key that was pressed by the user) with the string 'Y' .

So you can either compare the string playAgain (the user's answer) as-is:

if (playAgain === 'Y') {
  runGame()
} else {
  return false
}

Or, in case you'd like to accept both lower and upper case ( 'y' or 'Y' ) as valid answers, you'd invoke the .toLowerCase method:

// like this
if (playAgain.toUpperCase() === 'Y') {
  runGame()
} else {
  return false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM