How to use commander.js for building command-line interfaces in Node.js



Image not found!!

commander.js is a popular Node.js library for building command-line interfaces (CLIs). It provides a simple and expressive way to define and parse command-line options and arguments. Here's a basic guide on how to use commander.js:

Installation:

First, install commander using npm:

bash
npm install commander

Creating a Basic CLI:

Create a new file (e.g., cli.js) and require commander:

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

Adding Commands:

Define commands using the program.command() method. Here's an example with a simple "hello" command:

javascript
program .command('hello') .description('Prints a friendly greeting') .action(() => { console.log('Hello, world!'); });

Parsing Command Line Arguments:

Use program.parse(process.argv) to parse the command-line arguments. Add this line at the end of your script:

javascript
program.parse(process.argv);

Running the CLI:

Save the file and run it from the command line:

bash
node cli.js hello

Adding Options and Arguments:

You can add options and arguments to your commands. Here's an example with an option and an argument:

javascript
program .command('hello') .description('Prints a friendly greeting') .action(() => { console.log('Hello, world!'); });

Now you can run:

bash
node cli.js greet John -t Dr.

Handling Help:

commander.js automatically generates help information for your CLI based on the commands, options, and arguments you define. To display help, add the following code:

javascript
program.on('--help', () => { console.log(''); console.log('Examples:'); console.log(' $ node cli.js hello'); console.log(' $ node cli.js greet John -t Dr.'); });

Now, if you run:

bash
node cli.js --help

You'll see the help information.

This is a basic overview of using commander.js for building CLIs in Node.js. Depending on your use case, you might explore more features like option types, default values, required options, etc., as provided by commander.js. Check the official documentation for more details: commander.js documentation.