Ever wondered how those nice interactive terminal interfaces where you can select an option or mark a checkbox are made? I sure did and I found this awesome package: Inquirer.js
To be fair it's not a package, but rather a collection of several packages providing input, confirm, select, checkbox, file, password and more!
As usual install it using your favourite package manager, e.g. with deno add npm:@inquirer/prompts
.
Create a script, e.g. main.ts
:
import { input, select, confirm } from "@inquirer/prompts"; const name = await input({ message: "Enter your name:", required: true, validate: (v: string) => v.length > 1, }); const gender = await select({ message: "Choose your gender:", choices: ["Male", "Female", "Other"], }); await confirm({ message: "Is the information correct?", });
Run, e.g. with deno run -A ./main.ts
and enjoy:
β Enter your name: Valeria β Choose your gender: Female ? Is the information correct? (Y/n)
It comes with a built-in validator:
deno run -A ./main.ts ? Enter your name: V > You must provide a valid value
And with a little bit of extra code you can even make something like this:
import { input, select, confirm } from "@inquirer/prompts"; const getInput = async () => { const name: string = await input({ message: "Enter your name:", required: true, validate: (v: string) => v.length > 1, }); const gender: string = await select({ message: "Choose your gender:", choices: ["Male", "Female", "Other"], }); if ( !(await confirm({ message: "Is the information correct?", })) ) return getInput(); return { name, gender }; }; const data = await getInput(); console.log( `You are a great ${ { Male: "guy", Female: "gal", Other: "person" }[data.gender] }, ${data.name}!` );
Run it & tell me if you agree with the script ;-)
Liked the content and would love to have more of it all year long?
Top comments (0)