None Here’s a minimal, ready‑to-run boilerplate for a Node.js CLI tool using Commander.js.
1. Project structure
my-cli/
├─ bin/
│ └─ mycli.js
├─ src/
│ └─ index.js
├─ package.json
└─ README.md (optional)
2. package.json
{
"name": "my-cli",
"version": "0.1.0",
"description": "A sample Node.js CLI tool using Commander.js",
"bin": {
"mycli": "bin/mycli.js"
},
"type": "commonjs",
"scripts": {
"start": "node bin/mycli.js",
"dev": "NODE_ENV=development node bin/mycli.js"
},
"dependencies": {
"commander": "^12.0.0"
}
}
Install dependencies:
npm install
3. CLI entrypoint: bin/mycli.js
#!/usr/bin/env node
// Entry file that Node will execute when "mycli" is run.
// It simply delegates to the main CLI implementation.
require('../src/index');
Make it executable (Unix/macOS):
chmod +x bin/mycli.js
4. Commander setup: src/index.js
const { Command } = require('commander');
const pkg = require('../package.json');
const program = new Command();
program
.name('mycli')
.description('A sample CLI tool built with Commander.js')
.version(pkg.version)
.showHelpAfterError('(add --help for additional information)')
.showSuggestionAfterError();
// Global options (available to all commands)
program
.option('-d, --debug', 'enable debug output')
.option('-q, --quiet', 'suppress non-error output');
// Example "hello" command
program
.command('hello')
.description('Print a greeting')
.argument('[name]', 'name to greet', 'world')
.option('-u, --uppercase', 'print the greeting in uppercase')
.action((name, options, command) => {
const opts = command.parent.opts(); // global options
let message = `Hello, ${name}!`;
if (options.uppercase) {
message = message.toUpperCase();
}
if (!opts.quiet) {
console.log(message);
}
if (opts.debug) {
console.error('[debug] hello command executed');
}
});
// Example async command
program
.command('fetch')
.description('Simulate an async action (e.g., API call)')
.option('-t, --timeout <ms>', 'artificial delay in ms', '1000')
.action(async (options) => {
const delay = Number(options.timeout) || 1000;
console.log(`Starting async task (waiting ${delay} ms)...`);
await new Promise((resolve) => setTimeout(resolve, delay));
console.log('Async task finished.');
});
// Parse CLI arguments
program.parseAsync(process.argv).catch((err) => {
console.error(err instanceof Error ? err.message : String(err));
process.exitCode = 1;
});
5. Using the CLI locally
Run directly:
node bin/mycli.js --help
node bin/mycli.js hello
node bin/mycli.js hello Alice --uppercase
node bin/mycli.js --debug hello Bob
node bin/mycli.js fetch --timeout 500
Link globally (so you can run mycli from anywhere):
npm link
mycli --help
mycli hello
If you’d like this boilerplate using ES modules (type: "module") instead of CommonJS, I can provide that variant as well.