Building command-line tools

Intermediate · 6 min

Turn a Node script into a real CLI with a shebang and the bin field, parseArgs, readline prompts, exit codes, stdout versus stderr, and colour.

Before thisThe process objectThe util module

Codevolution · 6 min

Building command-line tools

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Node script becomes a command in three steps: a shebang line (`#!/usr/bin/env node`) on the first line, the executable bit on the file, and a `bin` entry in `package.json` so npm links it onto the `PATH` when the package is installed.
  • Read flags with `util.parseArgs` instead of hand-slicing `process.argv`. It handles `--name value`, `--name=value`, short aliases, repeated options and positionals, and it throws on unknown flags.
  • Prompt with `readline/promises` only when `process.stdin.isTTY` is true. Piped input needs a different approach (iterate lines), because a second `question()` on piped stdin can hang or never settle.
  • Be a good citizen of the shell: results to `stdout`, messages to `stderr`, exit code 0 on success and non-zero on failure, ideally 1 for runtime errors and 2 for bad usage. Set `process.exitCode` rather than calling `process.exit()` mid-output.
  • Handle Ctrl+C deliberately with a `SIGINT` handler that cleans up, and exit with 130 (128 + 2), which is what shells report for a process killed by SIGINT.

A script versus a tool

node greet.js --name Ada works, but nobody wants to type node and a path. A tool is something you can type by name, that tells you what is wrong in a way you can read, and that plays well with pipes and other programs. Node can do all of that with only built-in modules. This lesson was assembled and run on Node 26.13.1.

Make it a command

Three things turn a file into a command:

#!/usr/bin/env node
console.log('hello from a command');
  1. The shebang, #!/usr/bin/env node, must be the very first line. It tells the OS to run the file with whichever node is on the PATH. Node ignores it as a comment.
  2. The executable bit: chmod +x bin/greet.mjs. Without it, ./greet.mjs fails with “permission denied”. A file packed into an npm tarball keeps its mode, and npm sets the bit on bin targets when it links them.
  3. The bin field in package.json:
{
  "name": "greet-cli",
  "version": "1.0.0",
  "type": "module",
  "bin": { "greet": "./bin/greet.mjs" },
  "files": ["bin"]
}

When someone installs the package, npm creates a link named greet on their PATH (globally with npm install -g, or in node_modules/.bin for a local install). In a test, packing this folder with npm pack, installing the tarball into another project, and running ./node_modules/.bin/greet --name Ada printed Hello, Ada!, and the link was a symlink to the packaged bin/greet.mjs. During development, npm link does the same for your working copy. The files and bin fields are covered in package.json fields and exports, and publishing in publishing an npm package.

Parse flags with parseArgs

Reading process.argv[2] is fine for one argument. After that, use util.parseArgs, covered in the util module:

import { parseArgs } from 'node:util';

const { values } = parseArgs({
  options: {
    name: { type: 'string', short: 'n' },
    help: { type: 'boolean', short: 'h' },
    shout: { type: 'boolean' },
  },
});

if (values.help) {
  console.log('Usage: greet [--name <n>] [--shout]');
  process.exit(0);
}

It accepts --name Ada, --name=Ada and -n Ada, and throws for a flag you did not declare, so typos are not silently ignored. Catch that error and print the usage line instead of a stack trace. Remember all values are strings.

Prompt only when someone is there

Interactive prompts use node:readline/promises:

import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';

const rl = createInterface({ input: stdin, output: stdout });
const name = await rl.question('Your name? ');
rl.close();

Guard it with if (process.stdin.isTTY). If your tool is run in CI or from a pipe, there is no human, and a prompt would hang or fail. In that case require the value as a flag and exit with an error. There is also a trap with piped input. Running two await rl.question(...) calls with printf 'Ada\n36\n' | node cli.js printed the first prompt, then Node exited with code 13 and a “Detected unsettled top-level await” warning: both lines arrived at once, the first question consumed the first, and the second promise never settled. For non-interactive input, process lines as a stream instead:

const rl = createInterface({ input: process.stdin });
for await (const line of rl) console.log(line.toUpperCase());

That printed ADA and GRACE for the same piped input. Why streams explains why that works.

Be a good shell citizen

Four conventions make a tool composable:

  • Results to stdout, messages to stderr. If your tool’s output is piped into jq or another command, progress chatter or errors on stdout corrupt it. See the process object.
  • Exit codes mean something. 0 is success. Use non-zero for failure, commonly 1 for runtime errors and 2 for bad usage. Shell scripts and CI depend on it. Set process.exitCode = 2 and let the program end, rather than process.exit(2) in the middle of output.
  • Handle Ctrl+C. A SIGINT handler lets you remove temp files or restore the terminal, then exit with 130. In a test, process.on('SIGINT', () => { console.error('\ninterrupted'); process.exit(130); }) printed interrupted and the shell reported status 130.
  • Respect colour settings. Use util.styleText, which turns colour off when output is not a terminal or NO_COLOR is set, instead of hard-coding escape codes.

Here is a whole tool in one file, which was run in its interactive-failure and flag modes:

#!/usr/bin/env node
import { parseArgs, styleText } from 'node:util';
import { createInterface } from 'node:readline/promises';
import { stdin, stdout, stderr, exit } from 'node:process';

const { values } = parseArgs({
  options: { name: { type: 'string', short: 'n' }, help: { type: 'boolean', short: 'h' }, shout: { type: 'boolean' } },
});
if (values.help) { console.log('Usage: greet [--name <n>] [--shout]'); exit(0); }

let name = values.name;
if (!name) {
  if (!stdin.isTTY) { stderr.write(styleText('red', 'error: --name required when not interactive\n')); exit(2); }
  const rl = createInterface({ input: stdin, output: stdout });
  name = await rl.question('Your name? ');
  rl.close();
}
const msg = `Hello, ${name}!`;
console.log(values.shout ? msg.toUpperCase() : msg);

greet --name Ada --shout prints HELLO, ADA!; greet -h prints usage; greet < /dev/null prints the error to stderr and exits with status 2. For bigger tools with sub-commands, libraries such as Commander or yargs add help generation and nesting, but reach for them only once this stops being enough.

What the video covers

Codevolution’s six-minute video is a short chapter on building CLI tools in Node, and per its title it covers the basic building blocks. It was made in January 2023, and no transcript was available. The bin pipeline, parseArgs, styleText, the piped-input trap and the exit-code conventions are in the prose and were run on Node 26.13.1. Fireship’s five-minute CLI game under “go deeper” uses third-party prompt and colour packages that this lesson replaces with built-ins.

Where this fits

This closes the core-modules group before streams: you now have files, paths, events, bytes, utilities, crypto and a way to package them as a command. Why streams is next. Configuration for tools that read settings from the environment is in configuration and environment variables.

Check yourself

  1. 01You added `#!/usr/bin/env node` to `cli.js` and ran `./cli.js`, but got `permission denied`. What is missing?

    The executable bit. Run `chmod +x cli.js`. The shebang only tells the OS which interpreter to use once the file is allowed to run. When the file is installed through npm's `bin` field, npm sets the bit for you.

  2. 02How does a user get a `greet` command on their `PATH` after `npm install -g greet-cli`?

    The package's `package.json` has `"bin": { "greet": "./bin/greet.mjs" }`. On install, npm links `greet` to that file in a directory on the `PATH` (for a local install, into `node_modules/.bin`). The file needs the shebang line so the OS runs it with Node.

  3. 03Your CLI prints a JSON result and, on bad input, an error message. Where does each go, and what should the exit code be?

    The JSON result goes to `stdout` so it can be piped into other tools. The error message goes to `stderr`, so it does not corrupt the pipe. A usage error exits with a non-zero code such as 2, a runtime failure with 1, and success with 0.

  4. 04Why might `await rl.question(...)` twice in a row fail when input comes from `printf 'Ada\n36\n' | node cli.js`?

    Both lines arrive at once and the interface can consume the second line before the second question is asked. Then the stream ends and the second promise never settles. In a test Node exited with code 13 (unsettled top-level await). When stdin is not a terminal, read it with `for await (const line of rl)` instead.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark