You are currently viewing Getting Started with Node.js and Commander.js

Getting Started with Node.js and Commander.js

  • Post author:
  • Post category:Nodejs
  • Post comments:0 Comments
  • Post last modified:February 17, 2024

In this tutorial, we’ll explore how to build command-line interfaces (CLIs) in Node.js using Commander.js. Commander.js is a powerful library that helps in creating user-friendly command-line interfaces with ease. By the end of this tutorial, you’ll be able to create your own CLI application using Node.js and Commander.js.

Prerequisites

Before we begin, ensure you have Node.js installed on your system. You can download and install it from Node.js official website.

Installation

First, create a new directory for your project and navigate into it:

mkdir my-cli-app
cd my-cli-app

Initialize a new Node.js project:

npm init -y

Now, let’s install Commander.js:

npm install commander

Creating a Basic CLI Application

Now that we have Commander.js installed, let’s create a simple CLI application. We’ll build a command-line tool that greets the user with a customizable message.

Create a file named index.js in your project directory and open it in your favorite text editor.

In this code:

  • We imported Commander.js and initialized a program.
  • We defined the version and description of our CLI application.
  • We defined a command named greet which accepts an optional -n or --name option for specifying the user’s name.
  • When the greet command is executed, it logs a greeting message with the provided name or a default message if no name is provided.

Testing the CLI Application

Now, let’s test our CLI application. Run the following command in your terminal:

node index.js greet

You should see the output:

Hello, Stranger!

You can also specify your name using the -n or --name option:

node index.js greet --name Alice

Output:

Hello, Alice!

Conclusion

This is just a basic example to get you started. Commander.js provides many more features for building complex CLI applications, such as sub-commands, options, and more. You can explore the Commander.js documentation to learn more about its capabilities.

Leave a Reply