# Quick start:
# 1. Create a new directory: mkdir my-cli && cd my-cli
# 2. Copy the files below into the directory.
# 3. Run: npm install
# 4. Test locally: npm start -- hello World
# 5. Link globally for testing: npm link
# 6. Run globally: my-cli hello World
package.json
{
"name": "my-cli",
"version": "1.0.0",
"description": "A boilerplate Node.js CLI tool using Commander.js",
"main": "cli.js",
"bin": {
"my-cli": "./cli.js"
},
"scripts": {
"start": "node cli.js",
"dev": "node cli.js"
},
"keywords": ["cli", "commander", "nodejs"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"commander": "^12.1.0"
},
"engines": {
"node": ">=18.0.0"
}
}
cli.js
#!/usr/bin/env node
const { Command } = require('commander');
const program = new Command();
program
.name('my-cli')
.description('A boilerplate Node.js CLI tool using Commander.js')
.version('1.0.0');
program
.command('hello')
.description('Say hello to someone (or the world)')
.argument('[name]', 'name to greet', 'World')
.option('-f, --force', 'force a loud hello', false)
.action((name, options) => {
const greeting = options.force ? `HELLO, ${name.toUpperCase()}!` : `Hello, ${name}!`;
console.log(greeting);
});
program
.command('version')
.description('Output the current version')
.action(() => {
console.log(`v${program.version()}`);
});
// Add a root command example (runs if no subcommand)
program
.argument('[input...]', 'input string')
.option('-v, --verbose', 'verbose output')
.action((input, options) => {
if (input.length === 0) {
console.log('No input provided. Try: my-cli hello Alice');
program.help();
} else if (options.verbose) {
console.log('Verbose mode:', input.join(' '));
} else {
console.log('Echo:', input.join(' '));
}
});
// Parse arguments
program.parse(process.argv);
// Handle no command case
if (!process.argv.slice(2).length) {
program.help();
}
README.md (optional, for your repo)
# My CLI
A simple Node.js CLI tool built with [Commander.js](https://github.com/tj/commander.js).
## Installation
```bash
npm install -g my-cli
Usage
my-cli --help
my-cli hello [name] [--force]
my-cli version
my-cli "some input" [--verbose]
Development
npm install
npm start -- hello World
npm link # for global testing
Customization
- Add more commands:
program.command('newcmd').action(...)
- Global options:
program.option('--global-opt')
- Prompts: Integrate
prompts or inquirer
- Config: Use
cosmiconfig or rc
See Commander.js docs for advanced features.
## Key Features of This Boilerplate
- **Shebang** for Unix-like executable support.
- **npm bin** integration for global installs (`npm link` or `npm i -g`).
- **Subcommands** (`hello`, `version`) with arguments/options.
- **Root command** handling with fallbacks.
- **Help/version** auto-generated.
- **Minimal deps**: Only `commander`.
- **Modern Node.js** (ES2022+ compatible, tested on Node 18+).
Copy-paste these files, run `npm install`, and you're ready to extend! 🚀