How to Build an Efficient CLI with NodeJS?

Command-Line Interfaces or also known as CLIs (build in Node.js), gives developers a chance to automate all mundane tasks, and that too while leveraging the humongous Node.js ecosystem. The credit even goes to the package managers like yarn and npm, which helps CLI gets distributed and be used on different platforms seamlessly.

Hire Nodejs Developers

Why Create CLI with Node.js? 

Hire nodejs Developers

One of the most prominent reasons to use Node.js to create CLIs is its rich package ecosystem with more than 1.3 million packages in the npm registry. Just imagine how gigantic is the ecosystem that developers are stepping into with Node.js. 

This article is all about why a software developer would want to write a CLI, use Node.js for it, and distribute it without interruption. 

Prerequisites 

There are certain prerequisites to create CLI, so make sure you have them before you begin:

  • The latest version of Node.JS installed
  • A text editor

Let’s Set Up the Project Now

Nodejs Development Services

Here, we will be doing a setup of a basic Node.js project. Follow these steps for the same:

  1. Open Terminal 
  2. Create a folder for the project

~$mkdir termTranslate

  1. Navigate to it. 

~$cd termTranslate 

  1. Now, initialize a Node.js project in this newly created folder. 

~$npm init

  1. Fill in the prompt, and your project is all set up now. 
Now, Let’s Build the Basic CLI

Once the last step is done, and we have actually created the node project, it is time now to move to make the CLI. What you need to do is right here:

  1. Create a folder named ‘bin’ in the project’s root directory created in the step above. 
  2. Now, inside the bin folder, you need to create an index.js file that will act as the entry point of your new CLI. 
  3. In this step, you will have to open the package. json file to further modify the main part to bin/index.js. 
  4. Lastly, you will have to add another entity manually into the package.json file named bin. Set its key to tran and the value to ./bin/index.js. Here is what it must look like now:

“bin”: {  

    “tran”: “./bin/index.js”  

  }

So, the key, tran that we set in the step above, will act as the keyword for calling the CLI.  People will type this keyword in the terminal using the CLI. Besides, you can always choose the name for your choice; however, keeping it simple, short, and semantic is important to type and remember it easily. Also, you can change this name anytime you want. 

Command Line Arguments Handling 

We have prepared our CLI, and we will add other functionalities in the same. Also, the basic task for any CLI is to handle the command-line arguments. So, we will receive the language name in our CLI and the sentence that we need to translate. After that, we will parse it. 

We will use an npm package ‘yargs’ which is specially made for CLI creation. It will simplify the entire process of parsing the arguments and will help us manage and organize the command line flags. 

  1. Start by installing yargs

~$npm i yargs

  1. Include the module in index.js

~$const yargs = require(“yargs”);

  1. Now we will create the options object that includes all your command line flags

const usage = “\nUsage: tran <lang_name> sentence to be translated”;const options = yargs  

      .usage(usage)  

      .option(“l”, {alias:”languages”, describe: “List all supported languages.”, type: “boolean”,

demandOption

: false })                                                                                                    

      .help(true)  

      .argv;

In the code given above, we defined an option -I which will print every supported languages when passed by the API. Yargs helps us with –version and –help flags by default. 

Nodejs Development Services
Now, We Will Add Utility Functions

~$tran lang_name the sentence to be translated

Now, we will need to parse the arguments. So, here’s what we need to do:

  1. Create another file named utils.js in bin folder
  2. Include this file in your index.js

const utils = require(‘./utils.js’)

  1. Here, we create the function to parse the sentence. We will write the function in util.js before finally exporting it. 

module.exports = { parseSentence: parseSentence };function parseSentence(words) {  var sentence = “”; 

for(var i = 1; i < words.length; i++) {  

sentence = sentence + words[i] + ” “;  

 }

Now, call it in index.js

var sentence = utils.parseSentence(yargs.argv._);

Read our other post on Nodejs Advantages.

  1. In this step, we will create a function to help when we don’t pass any argument. The function will  be created in utils.js. 

module.exports = { showHelp: showHelp, parseSentence: parseSentence };const usage = “\nUsage: tran <lang_name

> sentence to be translated”;

function showHelp() {                                                            

    console.log(usage);  

    console.log(‘\nOptions:\r’)  

    console.log(‘\t–version\t      ‘ + ‘Show version number.’ + ‘\t\t’ + ‘[boolean]\r’)  

    console.log(‘    -l, –languages\t’ + ‘      ‘ + ‘List all languages.’ + ‘\t\t’ + ‘[boolean]\r’)  

    console.log(‘\t–help\t\t      ‘ + ‘Show help.’ + ‘\t\t\t’ + ‘[boolean]\n’)  

}

Now, call it in index.js

if(yargs.argv._[0] == null){  

    utils.showHelp();  

    return;  

}

Conclusion 

Hope this guide helped you learn how to create CLI in Node.js. This was a fully portable CLI and you can easily prepare it using these steps mentioned above. So, go ahead and try it yourself now! Happy coding!! 

At Your Team In India, we have a pool of certified Node.js engineers. Need help setting up a dedicated team of developers in India? Connect with us our business head now and get a free consultation.

Originally posted on YourTeam in India. Click here to read more.

Comments

Popular Posts