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
:
First, install commander
using npm:
bashnpm install commander
Create a new file (e.g., cli.js
) and require commander
:
javascriptconst { program } = require('commander');
Define commands using the program.command()
method. Here's an example with a simple "hello" command:
javascriptprogram
.command('hello')
.description('Prints a friendly greeting')
.action(() => {
console.log('Hello, world!');
});
Use program.parse(process.argv)
to parse the command-line arguments. Add this line at the end of your script:
javascriptprogram.parse(process.argv);
Save the file and run it from the command line:
bashnode cli.js hello
You can add options and arguments to your commands. Here's an example with an option and an argument:
javascriptprogram
.command('hello')
.description('Prints a friendly greeting')
.action(() => {
console.log('Hello, world!');
});
Now you can run:
bashnode cli.js greet John -t Dr.
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:
javascriptprogram.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:
bashnode 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.