Node.js CLI Tool with Commander
Build a type-safe CLI tool in Node.js using Commander.js with subcommands, option parsing, help generation, and TypeScript. Includes chalk-colored output.
Code
import { Command } from 'commander';
import chalk from 'chalk';
const program = new Command();
program
.name('mycli')
.description('A type-safe CLI tool')
.version('1.0.0');
program
.command('build <input>')
.option('-o, --output <path>', 'output directory', 'dist')
.option('--minify', 'minify output', false)
.action((input: string, opts: { output: string; minify: boolean }) => {
console.log(chalk.green(`Building ${input} → ${opts.output}`));
if (opts.minify) console.log(chalk.gray('Minification enabled'));
});
program.parse();Inside the snippet
Command are the only symbols borrowed from commander — the coupling is explicit and narrow.
Top-level bindings program hold the demo state — nothing sits inside a function scope.
Watch out for
- Plan for an install step:
commanderandchalkare a real dependency, resolved by the package manager.
Core lines
.action((input: string, opts: { output: string; minify: boolean }) => {
console.log(chalk.green(`Building ${input} → ${opts.output}`));
if (opts.minify) console.log(chalk.gray('Minification enabled'));
});
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there third-party dependencies?
- `commander` and `chalk` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.