Last active
May 28, 2021 19:02
-
-
Save crazy4groovy/d4410bae5ff455816fe8ac328c1fbc5c to your computer and use it in GitHub Desktop.
cli read line / ask question / user input (NodeJS)
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
// 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