DEV Community

Cover image for Building Your First CLI Tool
Anuradha Aggarwal
Anuradha Aggarwal

Posted on

Building Your First CLI Tool

Hello developers!! You must have use multiple CLI tools in your everyday development like echo, ls, cd etc.

Let’s try to understand it in a better way by creating your own simple CLI tool.

In this article, we will create a simple Calculator CLI tool.

🎯 What is CLI Tool?

A CLI (Command Line Interface) tool is just a program you run in the terminal by typing commands with your keyboard, instead of clicking buttons in a GUI (Graphical User Interface).

🎯 Project Setup

  1. Setup the Project with initial command
npm init
Enter fullscreen mode Exit fullscreen mode

Project Setup

  1. Create a folder named src in the root directory of your project.

  2. Inside src create a file called index.js This is going to be the entry point of our CLI.

  3. In the package.json file, change the “main” part to src/index.js.

  4. Now manually add another entry into the package.json file called bin and set its key to calc and it's value to ./src/index.js.

Your resultant package.json file would look like this:

{
  "name": "calculator-cli-tool",
  "version": "1.0.0",
  "description": "A CLI tool used for calculations",
  "main": "src/index.js",
  "bin": {
    "calc": "./src/index.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

The key calc, is the keyword for calling the CLI. This is the keyword that user will type in the terminal for using your CLI.

🎯 Commander

  • Commander is a popular Node.js library that makes it easy to build CLI tools.

What commander gives you?

  • Commands → Define sub-commands like add, multiply.
  • Arguments → Easily get values like 5 7.
  • Options (flags) → Support things like --verbose or --format json.
  • Automatic help → Generates --help output for free.
  • Versioning → Add --version easily.

Let’s install commander:

npm install commander
Enter fullscreen mode Exit fullscreen mode

In src/index.js file:

#!/usr/bin/env node
const { Command } = require('commander');
const program = new Command();

program
  .name('calc')
  .description('A simple calculator CLI')
  .version('1.0.0');

// Command: add
program
  .command('add <a> <b>')
  .description('Add two numbers')
  .action((a, b) => {
    console.log(Number(a) + Number(b));
  });

// Command: multiply
program
  .command('multiply <a> <b>')
  .description('Multiply two numbers')
  .option('-v, --verbose', 'Show detailed steps')
  .action((a, b, options) => {
    const result = Number(a) * Number(b);
    if (options.verbose) {
      console.log(`${a} * ${b} = ${result}`);
    } else {
      console.log(result);
    }
  });

program.parse();
Enter fullscreen mode Exit fullscreen mode

🎯 Link it globally

Now if you run the below command in your project folder, this creates a global symlink so you can use calc anywhere.

npm link
Enter fullscreen mode Exit fullscreen mode

Now your CLI tool is ready to use anywhere in your system. Let’s try it now:

🎯 CLI Building Blocks

CLI Building Block

As you noticed in the above examples, there are multiple parts in the single commands, let’s break it down.

  • calc is the main command (the tool itself).

  • add, multiply represents sub-command (an action inside calc).

  • 5, 7 represents the arguments (values you pass)

  • —verbose is a option which acts like a flag & modifies behavior

🎯 Wrap Up!!

That's all for this article. Thank you for your time!! Let's connect to learn and grow together. LinkedIn Twitter Instagram

Top comments (11)

Collapse
 
pranamyark profile image
Pranamya Rajashekhar

Ohhh this gives me so many ideas! Going to try it out for sure!

Collapse
 
ghotet profile image
Jay

I love this. I'm a big fan of using the terminal as much as possible but I never tried to make a program or tool directly inside it. I might have to give this a try.

Collapse
 
ddebajyati profile image
Debajyati Dey

Nice Write Up!

You may also like to have a read on my article that explores how to add oauth authnetication in your JS based CLI tools!

Collapse
 
bronlund profile image
Pal Bronlund • Edited

For the love of god, stop with the JavaScript all over the place already! It's made for doing stuff inside a browser, not for letting web developers ruin a perfectly good backend :)

Collapse
 
pjdeveloper896 profile image
Prasoon Jadon

Ohhh , nice , I am going to try this

Collapse
 
rationalkunal profile image
Kunal Kamble

Interesting and very beginner friendly!
I am also working on a CLI UI as my side project: github.com/rational-kunal/BlinkUI

Collapse
 
la_truonghoangphat_1cc9 profile image
La Truong Hoang Phat

Why u dont write bash/zsh script???

Collapse
 
masterdevsabith profile image
Muhammed Sabith

is it possible to make this in python ?

Collapse
 
nombrekeff profile image
Keff

Yup, most languages allow this!

Collapse
 
masterdevsabith profile image
Muhammed Sabith

I did one on python, 2 hours ago ! check it out on my profile

Collapse
 
masterdevsabith profile image
Muhammed Sabith

definitely gonna try it out ! saving this right now