Create a Command Line Interface (CLI) Using Node JS 01

Video Tutorial

Overview

In this Tutorial, we are gonna go through the process of making a command line interface (CLI) using Node JS using the help of the commander and inquirer modules that will allow us to submit commands and options alongside a very nice and flexible user interface (Not a graphical one!).

So we will try to implement an application that will allow us to manage contacts that has a name and a phone number so we can submit commands with custom options in order to either add, edit or delete an existing contact.

Getting Started

So first we need to set up a Node.JS app (you can learn more about node.js here) also we need MongoDB as a database for our contact to get stored in (also more on MongoDB here).

Make sure to create your working directory and initialize it with Node and MongoDB after that we need to install a couple of modules that we will work with

# Run...
npm install commander inquirer mongoose chalk figlet
## Chalk and Figlet are optional since they will help you prettify your app

Now we need to connect to our database and try to put on it manually some contacts that will help us debug our app quickly

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/contact_list", (err) => {
   if(err) console.error("Cannot connect to the database");
   else console.log("Connected to database");
});

Now consider putting this sample data on your database on a collection named contact_list since we are attempting to connect to it.

[{ name: "IslemPenywis", number: 29931952441 },
{ name: "Alex", number: 28003546431 },
{ name: "Mike", number: 2883158471 },
{ name: "Lily", number: 5383514251 },
{ name: "Chroose", number: 2565158471 },
{ name: "kris", number: 5623495321 }]

Please note the above step is optional you can do that automatically.

Now let’s create our Contact Collection Schema and Model.

//CREATE Schema
{
    name: {
        type: String,
        required: true
    },
    number: {
        type: String,
        required: true
    },
}
//Create Model
let Contact = mongoose.model("Contact", ContactSchema);

Ok, Everything is set up, now we can jump into our app.

Let’s create the CLI

Import commander and inquirer and let us try to add Contact Command so when we type: (node main.js addContact) we get asked about a couple of questions like (name and phone number).

const program = require("commander");
const inquirer = require("inquirer");

//We use the Command Method in order to register a command for our CLI 
program.command("addContact").description("Add new Contact").action(() => {
   //The Action method is going to fire up once our addContact command is submitted
   //Using Inquirer we ask questions and it will appear as a very nice Interface
   inquirer.prompt([ {type: "input", name: "Name", message:"Enter your Name..."}, 
                     {type: "input", name: "Name", message:"Enter your Name..."} ]).then((answers) => {
   //Log the received input for testing and using Chalk print with Colors :)
   console.log(chalk.green("Data: " + answers.name));
  });
}
/*The prompt method will take our object and convert it into a really nice input questions, you can use all sort of types (lists, checkbox...)*/

//Finally we need to pass in the arguments to the commander for parsing 
program.parse(process.argv);

Now we can run our app using node and pass it the addContact command.

node main.js addContact

You should get

It is very simple for creating such a command interface.

If you would like to pass in options (for e.x: — special or -s)

//you can use the option method separately or under the command method .option 
program.option("-s, --special").description("Special Contact");
program.parse(process.argv);
//to check for the option 
if(program.special) ///< Boolean TRUE | FALSE
//Or use it under the action 
program.action().option() ///< check for it in the same way

If you would like to save the added contact on the database create a new Instance and save it to the database.

//Cteate Instance and Save it to the database 
program.command("addContact").description("Add new Contact").action(() => {
    inquirer.prompt(questions).then((answers) => {
        console.log(chalk.green("Data " + answers.name));

        let contct = new Contact({
            name: answers.name,
            number: answers.number
        });
        contct.save((err, ct) => {
            if (err) console.error("Cannot Add new Contact");
            console.log(chalk.green("Contact Added Successfully! " + ct));
        });
    });
}

What’s Next

Since we have only covered the basics things about commander and inquirer in the next video we will finish our CLI by adding extra functionalities (getContacts, DeleteContacts).

No Comments Yet