Create an interactive CLI menu with Node.js

I have recently had to create an interactive menu for a project. I started programming it in bash and to tell the truth I quickly felt limited when I wanted to handle more complex cases and especially that I had to add more code from scratch. As the project is built in JavaScript, I told myself that there was probably a package that can do all what I want. After some research, I found it! The package is Inquirer.js. It’s a collection of common interactive command line user interfaces.

Here is a simple example with a list of choices

// assuming that `inquirer` has already been installed
const inquirer = require("inquirer");

inquirer
  .prompt([
    {
      type: "list",
      name: "prize",
      message: "Select a prize",
      choices: ["cake", "fries"]
    }
  ])
  .then((answers) => { 
    console.log(JSON.stringify(answers, null, "  "));
  });

What happens if we execute this code? Let’s see!

? Select a prize (Use arrow keys)
❯ cake 
  fries 

# if we select cake
# {
#  "prize": "cake"
# }

It doesn’t stop there, as it can handle multiple and different types of prompts. I highly recommend you to take a look on the project and the given examples https://github.com/SBoudrias/Inquirer.js/tree/master/packages/inquirer/examples

I hope it will be useful in your projects too!

Before you leave…
Thanks for reading! 😊