Skip to content

Instantly share code, notes, and snippets.

@romellem
Last active March 1, 2021 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romellem/c02497053f4b58188ac03b479c03720e to your computer and use it in GitHub Desktop.
Save romellem/c02497053f4b58188ac03b479c03720e to your computer and use it in GitHub Desktop.
Async Node.JS CLI Prompt / Question Using Built-in Modules
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