Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 133 ยท Compression, CLI and Tooling

Building Command-Line Tools

Build command-line tools with Node.js - parseArgs, subcommands, help text, exit codes, stdout vs stderr, colors with styleText, shebang bin entries and testing a CLI by spawning node.

Some of the most useful programs you will ever write have no window and no web page: a script that renames photos, a tool that checks your configuration, a command your whole team runs before every release. A command-line tool, or CLI, is a program you start from a terminal, steer with arguments and flags, and combine with other programs through text.

Node.js is a very good fit for this. Starting a script is quick, the standard library parses arguments for you, and the same language you use for servers works for tools. This lesson builds up a real CLI in small pieces: reading flags with parseArgs, splitting a tool into subcommands, writing helpful --help text, using exit codes and the two output streams correctly, adding color, wiring up a bin entry, and testing the whole thing by running it as a child process. If you have not yet used standard input, read Interactive CLIs with readline too; and the details of process.argv and exit codes are in The process Object.

Where arguments come from

When you run node tool.mjs build --out dist, Node gives your program an array called process.argv. The first two entries are the path to the Node executable and the path to your script; everything after that is yours. That is why tools slice off the first two:

Terminal
node tool.mjs build --out dist --verbose
# process.argv = ['/usr/bin/node', '/home/you/tool.mjs', 'build', '--out', 'dist', '--verbose']
# process.argv.slice(2) = ['build', '--out', 'dist', '--verbose']

You can split that array yourself, but you will quickly meet the awkward cases: --out=dist versus --out dist, short flags like -v, several short flags glued together as in -vq, flags that may repeat, and the -- marker that means "everything after this is not a flag". Since Node 18.3 (and stable in Node 20) the built-in parseArgs function from node:util handles all of these, so you do not need an npm package for ordinary tools.

Parsing flags with parseArgs

parseArgs takes an object with the args to parse and an options description. It returns values (the flags) and positionals (everything that is not a flag). In a real program you leave args out and it reads process.argv.slice(2) for you. In our examples we pass an array explicitly so the lesson is repeatable in the editor.

Node.js parseArgs: flags, values and positionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what each type gives you. A boolean flag is true when present and simply missing from values otherwise. A string flag takes the next argument (or the part after =). With multiple: true you always get an array. default fills in a value when the flag is absent, which is better than writing values.out ?? 'dist' in ten places.

By default parseArgs is strict. If a user mistypes a flag, it throws an error that you can turn into a friendly message. This is a feature: silently ignoring --verbos would be a bug.

Node.js Strict mode: unknown flags and missing values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each error carries a code such as ERR_PARSE_ARGS_UNKNOWN_OPTION, ERR_PARSE_ARGS_INVALID_OPTION_VALUE or ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL. The message already suggests how to fix the mistake, so most tools simply print it and exit.

parseArgs only knows two value types, string and boolean. Numbers arrive as strings, so convert them yourself with Number(...) and check the result with Number.isInteger or Number.isNaN. Validate early and exit with a clear message; Validating Input goes deeper on this.

Two more options are worth knowing. allowNegative: true lets --no-color switch off a boolean flag called color. And tokens: true returns the exact ordered list of what was parsed, which you need when the order of flags matters (for example, --include a --exclude b).

Subcommands

Tools such as git, npm and docker are really families of commands: git commit, git push. The pattern is simple. The first positional argument is the command name, and the remaining arguments belong to that command, which can parse them with its own options.

The trick is to stop parseArgs from treating the command name as an error and to hand the rest to the right parser. Here is a tiny to-do tool with two subcommands that works on an in-memory list.

Node.js A tool with add and list subcommands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the shape. A table of commands, each with its own option list and a run function, keeps the entry point tiny and makes adding a command a local change. A dedicated UsageError class separates mistakes by the user (print a message, exit with a code) from real bugs (let them crash with a stack trace). Typing errors from parseArgs itself can be wrapped the same way.

Help text and version

Every serious CLI answers --help and --version. Users learn a tool from its help, and a good help screen is the cheapest documentation you will ever write. Keep it short and put the most common thing first: a one-line usage, a list of commands, a list of options, and one or two examples.

Node.js Generating help text from the command table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Building the help from the same table that drives the dispatch means the documentation can never drift away from the code. Two conventions are worth following: --help prints to stdout and exits with code 0 (the user asked for it), while a usage mistake prints a short message to stderr and exits non-zero. We turn to exactly that next.

stdout, stderr and exit codes

Every process has two output channels. stdout is for the result of your program: the data someone might pipe into another program. stderr is for everything about the running of the program: progress messages, warnings, errors. The split matters because of pipes. In todo list --json | jq ., only stdout travels through the pipe; if you printed "Loading..." there, jq would choke on it.

In Node, console.log writes to stdout and console.error (and console.warn) write to stderr.

The exit code is a number the program leaves behind. Zero means success; anything else means failure. Shells, make, CI systems and && chains all depend on it. A sensible convention for your own tools:

Code Meaning
0 Success
1 General failure (something went wrong while working)
2 Misuse: bad flags, unknown command, missing argument

Set the code with process.exitCode = 2 and let the program end naturally. Avoid process.exit(2) in the middle of work, because it stops the process immediately and can cut off output that has not been flushed yet (especially when stdout is a pipe).

Our editor shows both streams mixed, so to see them apart we will let a script spawn a second copy of Node and capture each stream separately. This is also exactly how you test a CLI, which comes later.

Node.js Separating stdout, stderr and the exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The child printed three things, but the parent received them in two separate buffers, and the exit code arrived as a number. That is what a shell script or CI job sees.

Colors with styleText

Color makes output easier to scan: errors in red, success in green, secondary information dimmed. Node has a built-in helper, util.styleText(format, text), so you do not need chalk for simple cases. It adds the ANSI escape sequences that terminals interpret.

By default styleText is polite: if the stream you are writing to is not a terminal, or colors are disabled through the NO_COLOR or FORCE_COLOR environment variables, it returns the plain text. That is the behavior you want in a real tool, because the escape codes would otherwise end up in log files and pipes. In our editor the output is not a terminal, so we pass validateStream: false to force the codes and print them with JSON.stringify to make the invisible escapes visible.

Node.js styleText and the escape codes behind it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A reliable rule of thumb: color only when stdout (or stderr) is a TTY (process.stdout.isTTY), honor NO_COLOR, and never use color as the only way to carry meaning. Words like "error:" and "ok:" still help someone using a screen reader or a monochrome terminal.

Running as a real command: shebang and bin

During development you run node tool.mjs. To make it feel like a real command, two things are needed. The first line of the file is a shebang that tells Unix systems which program should run the file, and the file must be executable. In package.json, a bin field maps a command name to the file. Both snippets below are read-only, because installing commands needs npm and a file system that survives the run.

JavaScript
#!/usr/bin/env node
import { parseArgs } from 'node:util';

const { values } = parseArgs({ options: { name: { type: 'string', default: 'world' } } });
console.log(`hello, ${values.name}`);
JSON
{
  "name": "hello-cli",
  "version": "1.0.0",
  "type": "module",
  "bin": { "hello": "./bin/hello.js" },
  "files": ["bin"]
}

With that in place, npm link (while developing) or npm install -g hello-cli puts a hello command on your PATH, and npx hello-cli runs it without installing. On Windows, npm creates small wrapper scripts for you, so the shebang line is harmless there. On Unix, remember chmod +x bin/hello.js before publishing; npm sets the permission bit for files listed in bin when it installs the package.

Publishing a CLI follows the usual steps from Creating and Publishing Packages: choose a unique name, list only the needed files in files, set the engines field (for example "node": ">=22"), run npm pack --dry-run to see what would be uploaded, then npm publish. Keep dependencies few, because every one of them is downloaded on each npx run.

Testing a CLI by running it

You test a CLI at two levels. Pure logic, such as the command table above, can be tested by calling functions directly. But the wiring (argument parsing, streams, exit codes) is only truly tested by running the program the way a user does: as a separate process. The built-in child_process module can start Node itself, and you check three things: what went to stdout, what went to stderr, and the exit code.

The next example writes a small tool to disk, then runs it three times with different arguments and prints a compact report for each run.

Node.js Testing a CLI as a child process

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Turn these checks into real tests with the node:test runner: each test() runs the tool with some arguments and asserts on status, stdout and stderr. Because every run is a fresh process, tests are isolated and cannot leak state into each other. For speed, keep the heavy logic in importable functions and use only a few spawned runs as end-to-end checks.

Design habits of good CLIs

  • Be quiet when things work. Print results, not chatter. Offer --verbose for more and --quiet for less.
  • Fail loudly and early. Check arguments before doing any work, and say what to do: error: --port must be a number between 1 and 65535.
  • Support pipes. Read from stdin when no file is given, and print machine-readable output (--json) on request.
  • Never prompt when there is no terminal. Check process.stdin.isTTY before asking questions, or the tool will hang inside a CI job.
  • Handle Ctrl+C. Listen for SIGINT to clean up temporary files, then set a non-zero exit code. See Graceful Shutdown.
  • Do not hide the stack trace of real bugs. Expected user mistakes get a one-line message; unexpected errors should print the stack so they can be reported.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does process.argv.slice(2) contain when you run node tool.mjs build --out dist?

    The first two entries of process.argv are the Node executable and the script path. Everything after them is what the user typed for your program.
  2. 2. By default, what does parseArgs do when it meets a flag you did not declare?

    parseArgs is strict by default, so typos like --verbos are reported instead of being ignored. You can catch the error and print a friendly message.
  3. 3. Which output belongs on stderr?

    stdout carries the result, stderr carries diagnostics. With a pipe, only stdout is passed on, so mixing them would corrupt the data.
  4. 4. Why is setting process.exitCode usually better than calling process.exit(code) in the middle of a tool?

    Setting process.exitCode lets pending writes finish and the process end naturally with that code. process.exit terminates at once.
  5. 5. How do you reliably test the exit code and stderr of a CLI?

    Running the tool as a child process is the closest thing to what a user does, and it gives you each stream and the exit status separately.

Summary

  • process.argv.slice(2) holds your arguments; parseArgs from node:util turns them into values and positionals, with string and boolean types, short aliases, defaults and multiple.
  • parseArgs is strict by default and throws coded errors for unknown flags and missing values; catch them and print a clean message.
  • Model subcommands as a table of { options, run }, and generate help text from the same table.
  • Results go to stdout, diagnostics to stderr. Exit with 0 for success, 1 for failure and 2 for misuse, using process.exitCode.
  • util.styleText adds colors; respect NO_COLOR and only color real terminals.
  • A shebang line plus the bin field in package.json turns a script into an installable command.
  • Test a CLI by spawning process.execPath and checking stdout, stderr and the exit status.

Next: Intl, Dates and Formatting