Node.js theorytheory 0/50 · 0%
Tooling · medium

37. Building a CLI tool

Shebang lines, argument parsing and npm bin entries.

A Node script becomes an executable CLI with a shebang line (`#!/usr/bin/env node`) at the top, executable permissions, and a `"bin"` field in `package.json` mapping a command name to the script — `npm link` or a global install then makes it runnable by name.

js
#!/usr/bin/env node
const args = process.argv.slice(2);
const command = args[0];

if (command === "balance") {
  const address = args[1];
  console.log(`checking balance for ${address}`);
} else {
  console.log("usage: mytool balance <address>");
  process.exit(1);
}
json
{ "bin": { "mytool": "./cli.js" } }

For anything beyond trivial argument parsing, libraries like `commander` or `yargs` handle flags, subcommands, help text and validation far more robustly than hand-rolled `process.argv` slicing.

Check your understanding

  1. 1. What line at the top of a script tells the OS to run it with node?

  2. 2. Which package.json field maps a command name to a script for global installs?

  3. 3. Where do raw CLI arguments show up in a Node script?