Created
January 25, 2020 20:43
-
-
Save ehpc/ee42e86d07f85bf75b210b5f0397b0b4 to your computer and use it in GitHub Desktop.
Node.JS readline usage without recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const readline = require('readline'); | |
const questions = [ | |
['Can the fox be recursive?', 'O_o'], | |
['Can readline be non-recursive?', 'Yep'] | |
]; | |
const cmd = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
function askQuestion() { | |
if (!questions.length) { | |
return cmd.close(); | |
} | |
cmd.output.write(`${questions[0][0]} `); | |
cmd.resume(); | |
} | |
function checkAnswer(answer) { | |
if (answer === questions[0][1]) { | |
cmd.output.write('Correct!\n'); | |
} else { | |
cmd.output.write('Wrong!\n'); | |
} | |
questions.shift(); | |
cmd.pause(); | |
} | |
cmd.on('pause', askQuestion); | |
cmd.on('line', checkAnswer); | |
askQuestion(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment