You could write a reusable module like this:
// ask.js
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.pause();
function ask(question, cb = () => void 0) {
return new Promise(resolve => {
rl.question(question, (...args) => {
rl.pause();
resolve(...args);
cb(...args);
});
});
}
module.exports = ask;
And use it with multiple approaches everywhere:
Approach #1 (with async/await):
const ask = require("./ask");
(async () => {
const a = await ask("Enter the first number: ");
const b = await ask("Enter the second number: ");
console.log("The sum is", a + b);
})();
Approach #2 (with Promise):
const ask = require("./ask");
ask("Enter the first number: ")
.then(a => {
ask("Enter the second number: ")
.then(b => {
console.log("The sum is", a + b);
});
});
Approach #3 (with callback):
const ask = require("./ask");
ask("Enter the first number: ", a => {
ask("Enter the second number: ", b => {
console.log("The sum is ", a + b);
});
});