In the browser we have confirm() function which allows to provide a prompt string, and it returns either true/false.
I am trying to create a similar function for a NodeJS cli app. Below I am using readline module. Here is my code:
const readline = require('node:readline');
const rl = readline.createInterface({input: process.stdin, output: process.stdout});
let q = "Do you agree?";
function confirm(question) {
let options = ["yes", "y", "YES", "Y"];
let response;
rl.question(question, ans => {
response = ans;
console.log(`You responded with: ${ans}!`);
rl.close();
});
return options.includes(response);
}
let ans1 = confirm(q);
console.log(`ans1=${ans1}`);
let ans2 = confirm(q);
console.log(`ans2=${ans2}`);
For some reason it doesn’t work and the output generated is out of order also.
Do you agree?ans1=false
Do you agree?ans2=false
yes
You responded with: yes!
I suspect there is some async behaviour happening as we can see both prompt appear before readline callback is actually called.
How can I fix this?