This tutorial helps to create a command-line interfaces (CLIs) in Node.js. We’ll use Commander.js library to create a simple commander app in nodej.js. We’ll explore its features, syntax, and best practices to enable you to build powerful command-line applications.
What’s Commander.js
Commander.js is a popular Node.js library that helps with the creation of command-line interfaces (CLIs) with ease and elegance. This library is developed by created by the same person who created Express.js, TJ Holowaychuk.
The Features:
- Command: You can define commands and options in a declarative manner.
- Parse Arguments: This library parses parameters from the command line, handling flags, options, and arguments with ease.
-
CLI Versioning: You can set the version of your CLI application command-line arguments using the
version()
method. - Custom actions: Each command has a custom action that you may associate with it that executes out particular logic when the command is executed.
Getting Started with Commander.js
Let’s start diving into the Commander.js, Please make sure you have Node.js installed on your machine. You can initialize a new Node.js project by running the following command:
npm init -y
How To Install
Let’s install Commender.js into the nodejs application by running the following command:
npm install commander
Building Your First Commander.js CLI
Let’s create a simple command-line interface (CLI) tool that displays a simple hello message. Create a file named hello.js
and add the following code to this file:
#!/usr/bin/env node const { program } = require('commander'); program .version('1.0.0') .description('A simple CLI tool for hello message') .option('-n, --name <name>', 'Specify the name for the user') .parse(process.argv); const name = program.name || 'Adam Joe'; console.log(`Hello! ${name}!`);
In the above code, We have defined a simple CLI tool that displays a hello message with a name. Save the file and make it executable:
chmod +x hello.js
Run the above CLI file:
./hello.js -n Adam
Commander.js parses the command-line arguments and options and passes to the CLI app.
Conclusion
Commander.js simplifies the creation of a powerful and user-friendly command-line(CLI) app in Node.js. It supports declarative syntax, command line arguments, parse options and custom method logic.