Reading in input from the user can be done using prompt()
.
prompt() will only work in browsers, not in IDE's such as VSCode.
const iOSMessage = 'Looks like you develop for Apple devices.';
const webMessage = 'Hello, full stack dev.';
const input = Number(prompt('Please enter 1 for Swift or 2 for Web?'));
if (input === 1) {
console.log(iOSMessage);
} else {
console.log(webMessage);
}
Try it in repl.it
var readline = require("readline");
const r1 = readline.createInterface({
input: process.stdin,
output: process.stdout
});
r1.question('Do you want to hit or pass ?', (answer) => {
console.log(`You entered ${answer}`);
r1.close();
});
In order to create a looping structure e.g creating a Text Adventure game or a BlackJack game using readline
you must use a recursive function as a while
or do...while
won't execute continuosuly using readline
.
const gamePlay = function() {
r1.question('Enter yes or no?', (answer) => {
console.log(`You answered ${answer}`);
if (answer !== 'yes') {
return r1.close();
}
gamePlay();
});
};
gamePlay();