How to Build a CLI Tool with Node.js and Commander

Introduction

Command-line tools are essential for developer productivity. Node.js with Commander.js provides a clean API for building CLIs with subcommands, options, and help text.

Step 1: Set Up the Project

mkdir mycli && cd mycli
npm init -y
npm install commander chalk

Add a bin field to package.json:

{ "bin": { "mycli": "./dist/index.js" } }

Step 2: Define Commands

import { Command } from "commander";
import chalk from "chalk";

const program = new Command();

program
  .name("mycli")
  .description("A developer CLI tool")
  .version("1.0.0");

program
  .command("build <input>")
  .option("-o, --output <path>", "output directory", "dist")
  .option("--minify", "minify output", false)
  .action((input, opts) => {
    console.log(chalk.green(`Building ${input} → ${opts.output}`));
  });

program
  .command("deploy")
  .option("--env <environment>", "target environment", "production")
  .action((opts) => {
    console.log(chalk.blue(`Deploying to ${opts.env}`));
  });

program.parse();

Step 3: Test and Publish

node index.js build src --minify
node index.js deploy --env staging
npm link  # test locally
npm publish  # publish to npm

Conclusion

Commander.js makes it easy to build professional CLI tools in Node.js. The declarative API for commands and options, combined with chalk for colored output, creates a great developer experience.