Reputation: 15
I am trying to get started in Javascript by making a tic tac toe game on the console. This would require a while loop that takes in moves from the user.
This has proven to be much harder than I expected. Is there an easy way that I am missing.
I have tried using async.whilst, and sync-prompt. The former just sent me into an endless loop and the latter had errors when I tried using npm install to download it. Thanks for any help you can give!
Upvotes: 0
Views: 1837
Reputation: 138
I found this prompt-sync. It's not the same as the one you tried. In any case, if for some reason the npm installation fails, you can always grab the source code from its github page
It's not a perfect solution though, at least for me, as it doesn't catch accented characters or the spanish ñ character on the answer.
Anyways, this doesn't seem an easy task to do on node.
UPDATE: I found another way that works, at least for my purposes, since node 8, by using async and await combined with an IIFE:
(async function() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function prompt(message) {
return new Promise((resolve, reject) => {
rl.question(message, (answer) => {
resolve(answer);
});
});
}
var answer = await prompt("What do you have to say? ");
console.log("\nYou answered: \n" + answer);
rl.close();
})();
Upvotes: 0
Reputation: 945
You don't need to use a library. Just use node's built-in readline
.
Here's their example:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
Upvotes: 2