Last active
March 1, 2021 16:36
-
-
Save romellem/c02497053f4b58188ac03b479c03720e to your computer and use it in GitHub Desktop.
Async Node.JS CLI Prompt / Question Using Built-in Modules
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 { promisify } = require('util'); | |
const rl = require('readline'); | |
const readline = rl.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
}); | |
// Prepare readline.question for promisification | |
readline.question[promisify.custom] = (question) => { | |
return new Promise((resolve) => { | |
readline.question(question, resolve); | |
}); | |
}; | |
// Helper function for input prompts. Not required, can use `promisify(readline.question)(...)` directly. | |
const prompt = (prompt_str, append_trailing_space = true) => | |
promisify(readline.question)( | |
append_trailing_space ? String(prompt_str).trim() + ' ' : prompt_str | |
); | |
// For Node environments without top-level `await` | |
(async () => { | |
let answer = await prompt('What is your name?'); | |
console.log('You answered', answer); | |
// When you are done prompting for inputs, make sure to close your readline interface. | |
// Otherwise your process will not exit | |
readline.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment