How to create a command-line tool using the Commander.js library in Node.js



Image not found!!


Commander.js is a popular library for building command-line interfaces (CLIs) in Node.js. It simplifies the process of parsing command-line arguments and creating structured, user-friendly command-line tools. Here's a step-by-step guide on how to create a simple command-line tool using Commander.js:

  1. Initialize your Node.js project:

    Make sure you have Node.js installed on your machine. Create a new directory for your project and navigate into it using the terminal. Run the following commands to initialize a new Node.js project:

    bash
    npm init -y
  2. Install Commander.js:

    Install the Commander.js library using npm:

    bash
    npm install commander
  3. Create your CLI script:

    Create a new JavaScript file (e.g., cli.js) and open it in a code editor. This script will define and configure your command-line tool.

    javascript
    // cli.js const { program } = require('commander'); program.version('1.0.0'); // Define your command and options program .command('greet <name>') .description('Greet someone') .action((name) => { console.log(`Hello, ${name}!`); }); // Parse command-line arguments program.parse(process.argv);
  4. Add executable permission:

    Make your script executable by adding a shebang line at the top of the file and providing execute permissions. Open your terminal and run:

    bash
    chmod +x cli.js
  5. Run your CLI:

    Execute your CLI script with the following command:

    bash
    ./cli.js greet John

    This should output: Hello, John!

  6. Add more features:

    You can extend your CLI by adding more commands, options, and handling various scenarios. Here's an example of adding an optional --uppercase flag:

    javascript
    // cli.js const { program } = require('commander'); program.version('1.0.0'); program .command('greet <name>') .description('Greet someone') .option('-u, --uppercase', 'Print name in uppercase') .action((name, options) => { const greeting = `Hello, ${options.uppercase ? name.toUpperCase() : name}!`; console.log(greeting); }); program.parse(process.argv);

    Run the updated script with:

    bash
    ./cli.js greet John --uppercase

    This should output: Hello, JOHN!

Feel free to customize your CLI according to your needs, adding more commands, options, and logic. The Commander.js documentation (https://github.com/tj/commander.js/) is a valuable resource for exploring additional features and advanced configurations.