Node.js

Building CLI Tools with Node.js

Command-line interface (CLI) tools are essential for developers, enabling automation, task execution, and system management. With Node.js, building powerful and user-friendly CLI tools has never been easier. Libraries like Commander.js simplify the process of creating CLI applications, while npm makes publishing and distributing these tools a breeze. In this article, we’ll explore how to build CLI tools with Node.js, using Commander.js for command parsing and npm for distribution. We’ll also provide practical examples and best practices.

1. Why Build CLI Tools with Node.js?

Node.js is a popular choice for building CLI tools because:

  1. JavaScript Ecosystem: Leverage the vast npm ecosystem for dependencies.
  2. Cross-Platform: Node.js runs on Windows, macOS, and Linux.
  3. Ease of Use: JavaScript is widely known, making it accessible for developers.
  4. Scalability: Node.js is lightweight and efficient, ideal for CLI tools.

2. Getting Started with Commander.js

Commander.js is a popular library for building CLI tools in Node.js. It simplifies command parsing, option handling, and help text generation.

Installation

Install Commander.js using npm:

1
npm install commander

3. Building a Simple CLI Tool

Let’s create a basic CLI tool that greets the user.

Step 1: Set Up the Project

  1. Initialize a new Node.js project:
1
2
3
mkdir my-cli-tool
cd my-cli-tool
npm init -y

2. Install Commander.js:

1
npm install commander

Step 2: Create the CLI Tool

Create a file named index.js:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
!/usr/bin/env node
const { program } = require('commander');
 
program
  .name('greet')
  .description('A CLI tool to greet users')
  .version('1.0.0');
 
program
  .command('hello <name>')
  .description('Greet a user by name')
  .action((name) => {
    console.log(`Hello, ${name}!`);
  });
 
program.parse(process.argv);

Step 3: Make the Script Executable

Add a bin field to package.json to make the script executable:

01
02
03
04
05
06
07
08
09
10
{
  "name": "my-cli-tool",
  "version": "1.0.0",
  "bin": {
    "greet": "./index.js"
  },
  "dependencies": {
    "commander": "^10.0.0"
  }
}

Step 4: Test the CLI Tool

  1. Link the tool globally for testing:
1
npm link

2. Run the tool:

1
greet hello John

Output:

1
Hello, John!

4. Adding Advanced Features

1. Options and Flags

Commander.js makes it easy to add options and flags to your CLI tool.

Example: Add a --formal flag

01
02
03
04
05
06
07
08
09
10
11
program
  .command('hello <name>')
  .description('Greet a user by name')
  .option('-f, --formal', 'Use a formal greeting')
  .action((name, options) => {
    if (options.formal) {
      console.log(`Good day, ${name}.`);
    } else {
      console.log(`Hello, ${name}!`);
    }
  });

Usage

1
greet hello John --formal

Output:

1
Good day, John.

2. Subcommands

Organize your CLI tool with subcommands for better usability.

Example: Add a goodbye subcommand

1
2
3
4
5
6
program
  .command('goodbye <name>')
  .description('Say goodbye to a user')
  .action((name) => {
    console.log(`Goodbye, ${name}!`);
  });

Usage

1
greet goodbye John

Output:

1
Goodbye, John!

3. Input Validation

Validate user input to ensure correct usage.

Example: Validate the name argument

01
02
03
04
05
06
07
08
09
10
program
  .command('hello <name>')
  .description('Greet a user by name')
  .action((name) => {
    if (!name || name.length < 2) {
      console.error('Error: Name must be at least 2 characters long.');
      process.exit(1);
    }
    console.log(`Hello, ${name}!`);
  });

5. Publishing and Distributing CLI Tools via npm

Once your CLI tool is ready, you can publish it to npm for others to use.

Step 1: Create an npm Account

If you don’t have an npm account, sign up at https://www.npmjs.com/signup.

Step 2: Log in to npm

Log in to your npm account via the command line:

1
npm login

Step 3: Publish the Package

Run the following command to publish your CLI tool:

1
npm publish

Step 4: Install and Use the Tool

Others can now install your CLI tool globally using npm:

1
2
npm install -g my-cli-tool
greet hello Jane

6. Best Practices for Building CLI Tools

Best PracticeDescriptionExample
Use Commander.jsSimplify command parsing and option handling with Commander.js.Use program.option() to add flags.
Provide Help TextAutomatically generate help text for your CLI tool.Use program.description() and program.help().
Validate InputEnsure user input is valid before processing.Check if name is at least 2 characters long.
Use SubcommandsOrganize functionality into subcommands for better usability.Use program.command() to create subcommands.
Handle Errors GracefullyProvide meaningful error messages and exit codes.Use console.error() and process.exit(1) for errors.
Test ThoroughlyWrite unit tests for your CLI tool to ensure reliability.Use testing frameworks like Mocha or Jest.
Publish to npmDistribute your CLI tool via npm for easy installation.Use npm publish to share your tool.

7. Example: A Complete CLI Tool

Here’s a complete example of a CLI tool with multiple commands and options:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env node
const { program } = require('commander');
 
program
  .name('greet')
  .description('A CLI tool to greet and say goodbye to users')
  .version('1.0.0');
 
program
  .command('hello <name>')
  .description('Greet a user by name')
  .option('-f, --formal', 'Use a formal greeting')
  .action((name, options) => {
    if (!name || name.length < 2) {
      console.error('Error: Name must be at least 2 characters long.');
      process.exit(1);
    }
    if (options.formal) {
      console.log(`Good day, ${name}.`);
    } else {
      console.log(`Hello, ${name}!`);
    }
  });
 
program
  .command('goodbye <name>')
  .description('Say goodbye to a user')
  .action((name) => {
    console.log(`Goodbye, ${name}!`);
  });
 
program.parse(process.argv);

8. Useful Resources

  1. Commander.js Documentationhttps://github.com/tj/commander.js
  2. npm Documentationhttps://docs.npmjs.com/
  3. Node.js CLI Best Practiceshttps://blog.logrocket.com/building-node-js-cli-tools/
  4. Creating npm Packageshttps://docs.npmjs.com/creating-node-js-modules
  5. Testing CLI Toolshttps://www.npmjs.com/package/jest

By following this guide, you can build powerful and user-friendly CLI tools with Node.js, distribute them via npm, and streamline your development workflow. Start creating your own CLI tools today!

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Eleftheria Drosopoulou

Eleftheria is an Experienced Business Analyst with a robust background in the computer software industry. Proficient in Computer Software Training, Digital Marketing, HTML Scripting, and Microsoft Office, they bring a wealth of technical skills to the table. Additionally, she has a love for writing articles on various tech subjects, showcasing a talent for translating complex concepts into accessible content.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button