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.
Why Create CLI with Node.js?
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. (Source) 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
Recommended Read: How To Build CMS Using NodeJS
Let’s Set Up the Project Now
Here, we will be doing a setup of a basic Node.js project. Follow these steps for the same:
- Open Terminal
- Create a folder for the project
~$mkdir termTranslate
- Navigate to it.
~$cd termTranslate
- Now, initialize a Node.js project in this newly created folder.
~$npm init
- 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:
- Create a folder named ‘bin’ in the project’s root directory created in the step above.
- Now, inside the bin folder, you need to create an index.js file that will act as the entry point of your new CLI.
- In this step, you will have to open the package. json file to further modify the main part to bin/index.js.
- 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.
Know about the Growing Nodejs Development Trends here.
Now, after following all the steps, here is how your package.json file will look like:
{
"name": "termtran",
"version": "1.0.0",
"description": "A CLI to translate between languages in the terminal",
"main": "bin/index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [
"cli"
],
"bin": {
"tran": "./bin/index.js"
},
"author": "Your Name",
"license": "ISC"
}
Now, open the index.js file in the bin folder and use the following code in it:
#! /usr/bin/env node
console.log("Hello World!");
In this code, the #! Is known as the shebang line, which specifies the absolute path to the interpreter, which will help run the code.
After that, we will install the CLI and test it as well. For people to call CLI anywhere, we need to install it globally. Navigate to the root directory and then run the following code:
~$npm install -g
The -g flag will signal npm to install it in the system globally, and CLI can be tested by typing a keyword in the terminal.
~$tran
So, if you have been following everything correctly, you will see a message that we console.logged in the index.js file.
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.
- Start by installing yargs
~$npm i yargs
- Include the module in index.js
~$const yargs = require("yargs");
- 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.
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:
- Create another file named utils.js in bin folder
- Include this file in your index.js
const utils = require('./utils.js')
- 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