DEV Community

Cover image for Day 9: Terminal Forms ๐Ÿ“‡
Valeria
Valeria

Posted on

7 1 1 1 1

Day 9: Terminal Forms ๐Ÿ“‡

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?",
});
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

It comes with a built-in validator:

deno run -A ./main.ts
? Enter your name: V
> You must provide a valid value
Enter fullscreen mode Exit fullscreen mode

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}!`
);

Enter fullscreen mode Exit fullscreen mode

Run it & tell me if you agree with the script ;-)

Liked the content and would love to have more of it all year long?

Buy Me A Coffee

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)