Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active May 28, 2021 19:02
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 crazy4groovy/d4410bae5ff455816fe8ac328c1fbc5c to your computer and use it in GitHub Desktop.
Save crazy4groovy/d4410bae5ff455816fe8ac328c1fbc5c to your computer and use it in GitHub Desktop.
cli read line / ask question / user input (NodeJS)
// https://github.com/google/zx/blob/1508858ae964e49e0e5667860f7075b2a6aa15bf/index.mjs#L94
import {createInterface} from 'linebyline'
export async function question(query, options) {
let completer
if (Array.isArray(options?.choices)) {
completer = function completer(line) {
const completions = options.choices
const hits = completions.filter((c) => c.startsWith(line))
return [hits.length ? hits : completions, line]
}
}
const rl = createInterface({
input: process.stdin,
output: process.stdout,
completer,
})
const question = (qu) => new Promise((resolve) => rl.question(qu, resolve))
const answer = await question(query)
rl.close()
return answer
}
const name = await question('What is your name? ')
const fruit = await question('Fav fruit ', { choices: ['apples', 'bananas'] }) // tab completed choices
console.log(name + ' loves to eat ' + fruit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment