Blog / Javascript

How to Create a Command-Line Interface (CLI) Tool with Node.js and JavaScript

How to Create a Command-Line Interface (CLI) Tool with Node.js and JavaScript

In this post find out about how to Create a Command-Line Interface (CLI) Tool with Node.js and JavaScript

Will MaygerWill Mayger
May 30, 2023
Article

Command-Line Interface (CLI) tools are powerful applications that allow users to interact with software through a text-based interface. In this article, we will explore how to create a CLI tool using Node.js and JavaScript. We’ll cover the key concepts, tools, and steps involved in building a CLI tool from scratch.

Table of Contents

  • Introduction
  • Prerequisites
  • Setting up the Project
  • Understanding CLI Architecture
  • Building the CLI Tool
    • Handling User Input
    • Parsing Command-Line Arguments
    • Implementing Commands and Actions
    • Providing Help and Usage Information
    • Customizing Output and Formatting
  • Packaging and Distributing the CLI Tool
  • Conclusion

Introduction

CLI tools are widely used for a variety of purposes, such as automation, task management, and system administration. With Node.js and JavaScript, we can harness the power of the command line and build our own CLI tools to streamline tasks, automate workflows, and enhance productivity.

In this article, we’ll guide you through the process of creating a CLI tool using Node.js and JavaScript. We’ll cover the basics of CLI architecture, handling user input, parsing command-line arguments, implementing commands and actions, providing help and usage information, customizing output, and finally, packaging and distributing your CLI tool.

Prerequisites

Before we get started, make sure you have the following prerequisites:

  1. Node.js installed on your machine. You can download and install Node.js from the official website: https://nodejs.org

  2. Basic knowledge of JavaScript and the command line.

With these prerequisites in place, we’re ready to set up our project and start building our CLI tool.

Setting up the Project

To create a new Node.js project, open your terminal and follow these steps:

  1. Create a new project directory:

    mkdir cli-tool
    cd cli-tool
  2. Initialize the project with npm:

    npm init -y
  3. Install the necessary dependencies:

    npm install commander

We’ll be using the commander package, a popular library for building command-line interfaces in Node.js.

Understanding CLI Architecture

Before diving into the implementation details, let’s understand the basic architecture of a CLI tool. A typical CLI tool consists of the following components:

  1. Command: A command represents an action or task that the user wants to perform. For example, in a file management CLI tool, commands can include “list,” “create,” “delete,” etc.

  2. Options: Options modify the behavior of a command. They are usually preceded by a hyphen (-) or double hyphen (—). For example, in the command list --all, --all is an option that specifies listing all items.

  3. Arguments: Arguments are values passed to a command to perform a specific task. They provide additional information required to execute a command. For example, in the command create file.txt, file.txt is an argument specifying the filename.

  4. Help: The help command provides information about the available commands, options, and usage of the CLI tool. It helps users understand how to interact with the tool and its capabilities.

  5. Output: The CLI tool should provide informative and well-formatted output to the user. This includes displaying results, error messages, progress indicators, and any other relevant information.

Now that we have a basic understanding of CLI architecture, let’s start building our CLI tool step by step.

Building the CLI Tool

To create a CLI tool, we’ll use the commander package as the foundation.

It provides a simple and intuitive way to define commands, options, and arguments for our CLI tool.

Handling User Input

The first step is to handle user input. We can use the commander package to define our CLI program and specify the available commands, options, and arguments.

Create a new JavaScript file cli.js in your project directory and add the following code:

#!/usr/bin/env node

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

program.version('1.0.0');

// Define your commands, options, and arguments here

program.parse(process.argv);

In the above code, we import the program object from commander and set the version of our CLI tool to 1.0.0. You can modify the version according to your project.

Parsing Command-Line Arguments

Next, we need to parse the command-line arguments and perform the appropriate actions based on the user’s input.

To add a command, use the command method on the program object. For example, to add a greet command, update the code as follows:

program
  .command('greet')
  .description('Greet the user')
  .action(() => {
    console.log('Hello, user!');
  });

In the above code, we define a greet command with a description and an action. When the greet command is executed, it will log a greeting message to the console.

Implementing Commands and Actions

You can add multiple commands and actions to your CLI tool. For example, let’s add a time command that displays the current time:

program
  .command('time')
  .description('Display the current time')
  .action(() => {
    const currentTime = new Date().toLocaleTimeString();
    console.log(`The current time is: ${currentTime}`);
  });

In the above code, we define a time command that retrieves the current time and logs it to the console.

You can continue adding more commands and actions based on the functionality you want to provide in your CLI tool.

Providing Help and Usage Information

To provide help and usage information, you can use the built-in --help option provided by commander. It automatically generates the help information based on the commands, options, and arguments you defined.

To enable the --help option, add the following line before calling program.parse():

program.addHelpCommand(false);

By default, commander automatically adds a help command. By setting addHelpCommand to false, we disable the separate help command and enable the --help option instead.

Customizing Output and Formatting

You can further customize the output and formatting of your CLI tool. For example, you can add colors, tables, progress indicators, and more to enhance the user experience.

There are various third-party libraries available for formatting and beautifying the output. One popular library is chalk, which provides an easy way to add colors to your CLI output.

To install chalk, run the following command in your project directory:

npm install chalk

Then, you can use it in your code to add colors:

const chalk = require('chalk');

program
  .command('greet')
  .description('Greet the user')
  .action(() => {
    console.log(chalk.green('Hello, user!'));
  });

In the above code, we use chalk.green() to add a green color to the greeting message.

Feel free to explore other libraries and techniques to format and enhance the output based on your specific requirements.

Packaging and Distributing the CLI Tool Once you have completed building your CLI tool, you might want to package and distribute it so that others can use it.

You can use tools like pkg or nexe to package your Node.js code into an executable file for different operating systems. These tools bundle your code and dependencies into a single file, making it easy to distribute and run without requiring Node.js installation.

Consult the documentation of the packaging tool you choose for detailed instructions on how to package and distribute your CLI tool.

Conclusion

Congratulations! You have learned how to create a command-line interface (CLI) tool using Node.js and JavaScript. We covered the key concepts, tools, and steps involved in building a CLI tool from scratch.

By leveraging the commander package, you can define commands, options, and arguments for your CLI tool and provide a seamless user experience. Additionally, you explored techniques for handling user input, parsing command-line arguments, implementing commands and actions, providing help and usage information, and customizing the output and formatting.

With this knowledge, you can now embark on building your own CLI tools to streamline tasks, automate workflows, and enhance productivity.

Happy coding!

There we have how to Create a Command-Line Interface (CLI) Tool with Node.js and JavaScript, if you want more like this be sure to check out some of my other posts!

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app

Some graphics used on this post were made using icons from flaticon.

Latest Posts

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Become an expert in ReactJS, TypeScript, and JavaScript.

Here you will find my personal recomendations to you, for full disclosure I earn a small commission from some of these links, but I only recommend what I trust and personally use.

Good things are coming, don't miss out!

Good things are coming, don't miss out!

Follow me on Twitter to stay up to date and learn frontend, React, JavaScript, and TypeScript tips and tricks!

Are you a novice, intermediate or expert react engineer?

Find out here by taking my fun, interactive, quick quiz which takes approximately 1 - 3 minutes. How well will you will do?

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app