How-To Guide

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

Build a production-ready command-line tool in Node.js using Commander.js with subcommands, typed options, validation, exit codes, tests, and npm packaging.

On this page

  1. Introduction
  2. Why Commander instead of manual parsing
  3. Prerequisites and project layout
  4. Defining the command tree
  5. Typed options, validation, and environment defaults
  6. Errors, exit codes, and async actions
  7. Testing the CLI as a child process
  8. Packaging and publishing
  9. Common pitfalls
  10. Conclusion

Introduction

Command-line tools are the shortest path between a developer and an automated task. A good CLI accepts arguments predictably, prints useful help, fails with a meaningful exit code, and can be tested without a browser or a database. Node.js is a practical runtime for these tools because it is already present in most JavaScript build environments and ships with file-system, HTTP, and process APIs.

Commander.js is a small library that turns argument parsing into a declarative command tree. Instead of writing a chain of if statements over process.argv, you describe commands, arguments, and options once. Commander then generates help text, rejects unknown flags, validates choices, and routes execution to the correct action. This tutorial builds a small but complete CLI, adds typed validation and environment defaults, tests it as a child process, and packages it for npm.

Why Commander instead of manual parsing

Manual parsing looks simple until the tool grows. You need to handle --flag=value and --flag value, short aliases, repeated flags, -- to stop option parsing, unknown options, missing values, and help output. Each of those cases is a source of subtle bugs. A hand-written parser also tends to mix parsing with business logic, which makes both harder to test.

Commander provides a stable contract for those mechanics. Its help output is generated from the same definitions that drive parsing, so documentation cannot drift from behavior. Required options and enum choices are enforced before your action runs. Errors are written to stderr instead of stdout, which matters when the CLI is used in a pipeline. The library has no runtime dependencies and works with both CommonJS and ES modules.

The trade-off is that Commander is opinionated about command structure. That is usually an advantage for developer tools, but it may be unnecessary for a one-off script with a single argument. Choose Commander when the tool will be installed, shared, or extended.

Prerequisites and project layout

You need Node.js 20 or newer and npm. Create a package and enable ES modules so the examples run without transpilation:

mkdir taskctl && cd taskctl
npm init -y
npm pkg set type=module
npm pkg set bin.taskctl=bin/taskctl.js
npm install commander

Use a layout that separates the executable entry point from the implementation:

taskctl/
  bin/taskctl.js      # shebang + program.parseAsync
  src/commands.js     # command definitions and pure helpers
  test/cli.test.js    # child-process tests
  package.json

Add the shebang as the first line of bin/taskctl.js. Without it, Unix shells do not know how to execute the file after a global install. The bin field maps the command name to that file; npm creates the platform-specific shim when the package is installed.

Defining the command tree

A command tree should mirror the mental model of the user. The root command handles global concerns, while subcommands do one job each. The following example defines a build command with a required output format and a deploy command with an environment choice:

#!/usr/bin/env node
import { Command, Option } from 'commander';

const program = new Command();

program
  .name('taskctl')
  .description('Build and deploy tasks')
  .version('1.0.0')
  .showHelpAfterError('(run taskctl --help for usage)');

program
  .command('build')
  .description('Build a project')
  .argument('<input>', 'entry file')
  .addOption(
    new Option('-f, --format <type>', 'output format')
      .choices(['esm', 'cjs'])
      .default('esm')
  )
  .option('-o, --output <dir>', 'output directory', 'dist')
  .option('--minify', 'minify the output', false)
  .action(async (input, options) => {
    console.log(JSON.stringify({ input, ...options }));
  });

program
  .command('deploy')
  .description('Deploy a build')
  .requiredOption('-e, --env <name>', 'target environment')
  .option('--dry-run', 'print the plan without deploying', false)
  .action(async (options) => {
    console.log(JSON.stringify({ deploy: options.env, dryRun: options.dryRun }));
  });

await program.parseAsync(process.argv);

The action receives positional arguments first and the command options object second. Keeping the action thin is deliberate: it should parse inputs, call a function, and translate the result into output and an exit code. Business logic belongs in a separate module so it can be tested without spawning a process.

Typed options, validation, and environment defaults

Commander passes option values as strings unless you provide a parser. That is a common source of bugs: --port false becomes the string "false", and --retries 3 becomes "3". Use custom parsers to convert and validate at the boundary:

import { InvalidArgumentError } from 'commander';

function positiveInt(value) {
  const parsed = Number.parseInt(value, 10);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    throw new InvalidArgumentError('Expected a positive integer.');
  }
  return parsed;
}

program
  .option('-p, --port <number>', 'port to listen on', positiveInt, 3000)
  .option('--retries <number>', 'retry count', positiveInt, 3);

Environment variables are useful for CI, but they should not bypass validation. Read the environment while defining the option and pass the value through the same parser:

const defaultPort = positiveInt(process.env.TASKCTL_PORT ?? '3000');

program.option('-p, --port <number>', 'port to listen on', positiveInt, defaultPort);

For boolean environment flags, compare explicitly against "1" or "true" instead of relying on truthiness. The string "false" is truthy in JavaScript, which has caused more than one production surprise. Also avoid putting secrets in command-line arguments: process arguments are visible to other users on many systems through the process list. Read secrets from the environment or a file descriptor.

Errors, exit codes, and async actions

A CLI has three kinds of failure: invalid usage, an expected runtime failure, and an unexpected crash. They deserve different exit codes. A common convention is 2 for usage errors, 1 for runtime failures, and 0 for success. Scripts and CI systems can then distinguish “the user typed the command wrong” from “the operation failed”.

Commander writes usage errors to stderr and exits non-zero by default. For domain failures, catch the error in the action, print a concise message to stderr, and set process.exitCode:

program.command('check').action(async () => {
  try {
    await runChecks();
  } catch (error) {
    console.error(`check failed: ${error.message}`);
    process.exitCode = 1;
  }
});

Use parseAsync when any action is asynchronous. parse does not await promises, so a rejected promise can escape the process with an unhelpful stack trace. Reserve console.log for machine-readable output and console.error for diagnostics; mixing the two corrupts JSON output consumed by another program. If you support --json, do not print progress messages to stdout in the same mode.

Testing the CLI as a child process

Unit tests for helper functions are valuable, but they do not prove that the command tree, help output, and exit codes work. Add at least a few child-process tests with the built-in node:test runner:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

test('build prints a JSON plan', async () => {
  const { stdout } = await run(process.execPath, [
    'bin/taskctl.js', 'build', 'src/index.js', '--format', 'cjs'
  ]);
  const plan = JSON.parse(stdout);
  assert.equal(plan.input, 'src/index.js');
  assert.equal(plan.format, 'cjs');
});

test('unknown options exit with a usage error', async () => {
  await assert.rejects(
    run(process.execPath, ['bin/taskctl.js', 'build', '--nope']),
    (error) => error.code !== 0
  );
});

Use execFile rather than exec so arguments are passed as an array and never interpreted by a shell. Set NO_COLOR=1 in the test environment when the output includes color codes, and assert on exit codes as well as text. If the CLI writes files, run it in a temporary directory so tests do not depend on repository state.

Packaging and publishing

Before publishing, verify the package contents with npm pack --dry-run. The tarball should contain the bin file, the source it imports, the README, and the license, and it should not contain tests, local configuration, or secrets. The files field is an allowlist:

{
  "name": "taskctl",
  "version": "1.0.0",
  "type": "module",
  "bin": { "taskctl": "bin/taskctl.js" },
  "files": ["bin", "src", "README.md", "LICENSE"],
  "engines": { "node": ">=20" }
}

Run npm link during development to test the global command, then npm publish --access public for a public package. On Windows, npm creates .cmd and PowerShell shims, so test the installed command there if Windows is a supported platform. Document the Node version in engines; a CLI that relies on modern APIs will fail confusingly on older runtimes otherwise.

Common pitfalls

  • Missing shebang or wrong bin path. The command exists after install but the shell reports “not found” or tries to run the file as a shell script.
  • Commander installed as a dev dependency. A globally installed CLI must declare runtime dependencies in dependencies, not devDependencies.
  • Boolean parsing by truthiness. --flag false is still a truthy string. Use a parser or a separate negated flag.
  • Logs on stdout. JSON output and progress messages must not share the same stream.
  • Unvalidated paths. A CLI that writes to a user-supplied path must resolve it and reject traversal outside the intended directory.
  • Secrets in argv. Passwords passed as arguments leak through process listings, shell history, and CI logs.

Conclusion

Commander gives a Node.js CLI a clear command tree, generated help, and consistent error handling without adding a runtime dependency. The important engineering work happens around the parser: validate values at the boundary, keep business logic separate from the action, use exit codes deliberately, and test the installed behavior as a child process. Once those pieces are in place, packaging the tool is a small final step.

Sources: Commander.js documentation, Node.js child_process documentation, npm package.json bin field.

FAQ

Should a Node.js CLI use Commander or parse process.argv manually?
Use Commander once you have more than one command or option. Manual parsing is fine for a single flag, but Commander provides help, version output, required options, choices, and consistent usage errors that are easy to get wrong by hand.
How do I read environment variables in a Commander CLI?
Read process.env while building options and pass the value as the option default. Validate the result with the same parser used for explicit flags so environment variables cannot bypass validation.
Why does my CLI work with node but fail after npm install?
The most common causes are a missing shebang, a bin path that does not match the published file, or a package marked as an ES module without using ESM imports. Check the bin field, the first line of the entry file, and the package type.

Related Examples

Interactive Tools for This Topic