Let's Build A CLI - Command Line Interface With Node - Js - by Manav Shrivastava - Medium
Let's Build A CLI - Command Line Interface With Node - Js - by Manav Shrivastava - Medium
Node.js
Manav Shrivastava · Follow
4 min read · Mar 29, 2022
We use command-line utilities every day, whether it be git, grep, awk, npm, or any other terminal
app.
CLIs are super useful and usually the fastest way to get something done.
Today we will learn how can we create our own CLI tool.
~$mkdir mycli
3. Navigate to it.
~$cd mycli
~$npm init
2. Inside bin create a file called index.js This is going to be the entry point of our CLI.
3. Now open the package.json file and change the “main” part to bin/index.js .
4. Now manually add another entry into the package.json file called bin and set its key
to mycli and it's value to ./bin/index.js . The addition should look something like this:
"bin": {
"mycli": "./bin/index.js"
}
The key, mycli , is the keyword for calling the CLI. This is the keyword that people will type in
the terminal for using your CLI. Be free to name it whatever you like, although I would suggest
keeping the name short
and semantic so that it’s quick to type and easy to remember.
The name defined here is not permanent and can be changed whenever you like.
People may call our CLI from anywhere in the system so let’s install it globally.
~$npm install -g .
The -g the flag tells npm to install the package globally on the system.
~$mycli
The most basic task that any CLI does is handling command-line arguments. In our CLI, we will be
receiving the language name and the sentence to be translated as arguments and then we will parse it.
Although Node.js offers built-in functionality for handling command-line arguments, we are going to
use an npm package called yargs 🏴☠ which is specifically made for building CLI
s. yargs will simplify our process of parsing arguments and help us organize command-line flags.
1. Install yargs
~$npm i yargs
3. Then create the options object containing all your command line flags:
.usage(usage)
.option("l", {alias:"language", describe: "Translate to language", type:
"string", demandOption: false })
.help(true)
.argv;
In the above code, I have defined an option -l which, when passed will print all the supported
languages by the API, we will implement this later. Yargs provides us with --help and --
If you want an option to be compulsory then you can set it’s demandOption value to true , this will
get yar
gs to throw a Missing argument error if the flag is not provided.
mycli <command>
mycli demo
Hope you had fun learning how to build your own CLI :)
Happy coding!
Here’s a list of the packages you can use specifically for developing the command-line tool:
chalk — colorizes the output
configstore — easily loads and saves config without you having to think about where and how.