Creating CLI Tools in Node.js
Build and publish Node.js command-line tools: shebang, package.json bin, commander.js arguments, colored output, prompts, testing, and npm publishing.
By Velloreth
A command-line tool is the smallest useful piece of software you can publish: one file, no frontend, no API, just input and output. If you can write a Node script, you can write a CLI.
This tutorial builds a real tool called site-check that probes a URL and reports whether it is up, how long it took, and what status code it returned. Along the way it covers the shebang, package.json bin, argument parsing with commander.js, colored output, prompts, testing, and publishing. Every command runs.
What you need
| Requirement | Version | Check with |
|---|---|---|
| Node.js | 22.12.0 or newer | node -v |
| npm | 10 or newer | npm -v |
Create the project:
mkdir site-check && cd site-check
npm init -y
npm install commander is-https
npm install --save-dev @types/node typescript tsx
commander parses flags and arguments and prints help automatically. is-https is a tiny dependency that proves the point about keeping dependencies minimal — you could replace it with Node’s built-in https module, but for a tutorial it keeps the example focused.
Step 1: Make it executable
A Node script becomes a CLI with one line at the top and one entry in package.json. Create src/index.ts:
#!/usr/bin/env node
import { program } from 'commander';
import https from 'node:https';
import http from 'node:http';
program
.name('site-check')
.description('Check if a website is up and report response time')
.version('0.1.0');
program
.argument('<url>', 'URL to check')
.option('-t, --timeout <ms>', 'request timeout in milliseconds', '5000')
.action(async (url, options) => {
const start = Date.now();
try {
const status = await check(url, Number(options.timeout));
const ms = Date.now() - start;
console.log(`${url} ${status} in ${ms}ms`);
} catch (err) {
console.error(`${url} failed: ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
}
});
function check(url: string, timeout: number): Promise<number> {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const lib = parsed.protocol === 'https:' ? https : http;
const req = lib.get(parsed, { timeout }, (res) => {
resolve(res.statusCode ?? 0);
});
req.on('timeout', () => {
req.destroy(new Error('timeout'));
});
req.on('error', reject);
});
}
program.parse(process.argv);
The first line, #!/usr/bin/env node, is the shebang. It tells the operating system to run the file with Node. Everything after it is ordinary TypeScript.
Now the bin field in package.json:
{
"name": "site-check",
"version": "0.1.0",
"bin": {
"site-check": "./dist/index.js"
},
"type": "module"
}
bin maps a command name to the file that runs when someone types site-check. The type: "module" line lets you use import syntax; match it to your module setup.
Compile and run:
npx tsc --init --target ES2022 --module ESNext --moduleResolution bundler --outDir dist --strict
npx tsc
chmod +x dist/index.js
./dist/index.js https://example.com --timeout 3000
Expected output:
https://example.com 200 in 214ms
Run it with no arguments and commander prints usage and exits:
Usage: site-check [options] <url>
Arguments:
url URL to check
Options:
-t, --timeout <ms> request timeout in milliseconds (default: "5000")
-v, --version output the version number
-h, --help display help for command
That help block came free. Without commander you would write it yourself and keep it in sync by hand.
Step 2: Colors and formatting
Raw console.log is functional but hard to scan. Add color only for direct terminal output, never for piped output. picocolors is lightweight and dependency-free:
npm install picocolors
import { green, red, yellow, bold } from 'picocolors';
const ms = Date.now() - start;
const color = status >= 200 && status < 400 ? green : red;
console.log(`${bold(url)} ${color(status)} in ${ms}ms`);
Check whether stdout is a TTY before adding color:
const useColor = process.stdout.isTTY;
When you pipe the output to a file, strip the ANSI codes so the next program in the pipeline reads plain text:
site-check https://example.com > results.txt
results.txt should contain no escape sequences. A CLI that colors piped output breaks grep, awk, and anything else reading its output.
Step 3: Subcommands
One tool, one job is a good rule, but related jobs belong under one command. Add a history subcommand that shows recent checks:
program
.command('history')
.description('show recent checks')
.option('-n, --count <number>', 'how many to show', '10')
.action((options) => {
console.log(`showing last ${options.count} checks`);
});
Now site-check history -n 5 works, and site-check --help lists both check (the default argument form) and history. Commander nests help automatically.
If a subcommand grows large enough to deserve its own file, commander supports stand-alone executable subcommands named site-check-history, but start with an action handler and split out only when the file is actually long.
Step 4: Interactive prompts
Some flags are easier to ask for than to remember. Add an optional interactive mode with the prompts package:
npm install prompts
npm install --save-dev @types/prompts
import prompts from 'prompts';
if (options.interactive) {
const answer = await prompts([
{
type: 'text',
name: 'url',
message: 'URL to check',
validate: (value) => value.startsWith('http') || 'must start with http',
},
]);
// run check with answer.url
}
Use prompts sparingly. A CI pipeline cannot answer a prompt, and anything that runs unattended must work entirely from flags. Make interactive mode opt-in with a flag like --interactive, never the default.
Step 5: Tables and progress
If your tool lists more than three things, use a table. cli-table3 renders bordered tables in the terminal:
npm install cli-table3
import Table from 'cli-table3';
const table = new Table({
head: ['URL', 'Status', 'ms'],
colWidths: [40, 10, 10],
});
table.push(['https://example.com', '200', '214']);
table.push(['https://httpbin.org/status/500', '500', '890']);
console.log(table.toString());
For long-running work, a spinner beats a blank screen. ora shows one:
npm install ora
import ora from 'ora';
const spinner = ora('Fetching...').start();
await check(url);
spinner.stop();
Stop the spinner before printing the result, or the final line overwrites the animation and leaves a half-rendered frame in the terminal.
Step 6: Test without clicking
Split the core logic from the CLI wiring. check is already a pure function, so unit test it directly:
import { test, expect } from 'node:test';
import assert from 'node:assert';
test('check resolves with status code', async () => {
// spin up a tiny local server in the test, call check, assert status
});
For end-to-end behavior, spawn the compiled binary and assert on exit code and output:
import { execFileSync } from 'node:child_process';
const out = execFileSync('node', ['dist/index.js', 'https://example.com'], {
encoding: 'utf8',
});
assert.ok(out.includes('200'));
Test the error path too: a bad URL should exit non-zero and print to stderr. A CLI that exits 0 on failure silently breaks scripts that depend on set -e.
Step 7: Publish
Build, then publish:
npx tsc
npm publish --access public
Anyone can now run:
npx site-check https://example.com
npx downloads the package, finds the bin entry, and executes it. No npm install -g, no shell script, no version management for the consumer.
Before publishing, check three things:
- The
binfile is executable (chmod +x) and the path inpackage.jsonmatches the compiled output. - The shebang is present and correct.
- You are not committing secrets — environment variables for API keys, never hardcoded strings.
To test locally before publishing, run npm link in the project folder. It symlinks the package into your global node_modules so site-check works as if it were published, without touching npm.
What to keep small
The best CLI tools do one thing and finish quickly. Do not add a configuration file format until users ask for one. Environment variables cover most customization:
const timeout = process.env.SITE_CHECK_TIMEOUT ?? '5000';
Avoid heavy frameworks, GUI wrappers, and auto-updaters. A CLI tool that starts in under a hundred milliseconds and prints one clear line is more useful than a bloated one that does five things poorly.
Publish it, write a one-line README with an example invocation, and move on. The tool is done when someone else can run npx site-check and get an answer without reading documentation.