Creating a Command-Line Interface (CLI) Tool with NodeJS: A Step-by-Step Guide

December 01, 2024By Rakshit Patel

Command-line interface (CLI) tools are essential for developers, providing a way to automate tasks, interact with
applications, and streamline workflows. In this guide, we will walk you through the process of creating a simple CLI
tool using Node.js.

Prerequisites

Before you start, make sure you have the following installed:

  • Node.js (latest version)
  • A text editor (like Visual Studio Code, Atom, or Sublime Text)
  • Basic knowledge of JavaScript and the command line

Step 1: Set Up Your Project

1. Create a new directory for your project:

mkdir my-cli-tool
cd my-cli-tool

2. Initialize a new Node.js project:

npm init -y

This will create a package.json file in your project directory.

3. Install necessary dependencies:

For this tutorial, we’ll use the commander package for command-line argument parsing.
npm install commander

Step 2: Create the CLI Script

1. Create a new JavaScript file for your CLI tool:

touch index.js

2. Open index.js in your text editor and add the following code:


#!/usr/bin/env node

const { Command } = require('commander');
const program = new Command();

// Define CLI commands and options
program
.version('1.0.0')
.description('A simple CLI tool example')
.option('-n, --name ', 'specify a name')
.option('-g, --greet', 'greet the user');

// Handle the command and options
program.action(() => {
    if (program.greet && program.name) {
        console.log(`Hello, ${program.name}!`);
    } else if (program.greet) {
        console.log('Hello, World!');
    } else {
        console.log('No greeting specified.');
    }
});

program.parse(process.argv);

In this code:

  • We import the commander package and create a new command program.
  • We define a version, description, and options for the CLI tool.
  • The action method handles the logic based on user input.

Step 3: Make the Script Executable

1. Add the following line at the top of index.js:

#!/usr/bin/env node

This shebang line allows the script to be run as an executable from the command line.

2. Make your script executable by running the following command:

chmod +x index.js

Step 4: Link the CLI Tool Globally

1. Update your package.json to include a bin field:

Add the following to your package.json:

"bin": {
"my-cli-tool": "./index.js"
}

Replace "my-cli-tool" with the desired name for your CLI command.

2. Link your package globally:

Run the following command:

npm link

  1. This command makes your CLI tool accessible from anywhere in the terminal.

Step 5: Test Your CLI Tool

1. Run your CLI tool from the terminal:

You can greet the user by specifying a name:

my-cli-tool --greet --name John

This should output:

Hello, John!

2. Try other variations:

  • Just greet without a name:

my-cli-tool --greet

Output:

Hello, World!

  • Call the tool without the greet option:

my-cli-tool

Output:

No greeting specified.

Step 6: Expand Your CLI Tool

Now that you have a basic CLI tool, you can expand its functionality by adding more commands and options. Here
are a few ideas:

  • Add more commands using program.command('commandName').
  • Include file handling to read or write data.
  • Integrate APIs or external services.
  • Implement logging or configuration options.

Conclusion

Congratulations! You’ve built a simple CLI tool using Node.js. This guide has covered the basics, but the
possibilities are endless. With commander and Node.js, you can create robust command-line
applications tailored to your needs. Explore more features, enhance your tool, and make it a powerful addition
to your development toolkit. Happy coding!

Rakshit Patel

Author ImageI am the Founder of Crest Infotech With over 15 years’ experience in web design, web development, mobile apps development and content marketing. I ensure that we deliver quality website to you which is optimized to improve your business, sales and profits. We create websites that rank at the top of Google and can be easily updated by you.

CATEGORIES