CLI Tools
Building command-line tools with process.argv, readline, and formatted output
Skills taught: node.process-argv, node.cli-args, node.readline, node.cli-output
Building a CLI tool
#!/usr/bin/env node
// ^^^ Shebang: tells the OS to run this file with Node.js
// Simple arg parser
const args = process.argv.slice(2); // skip ['node', 'script.js']
// Usage: node cli.js greet --name Alice --shout
const command = args[0];
const nameIdx = args.indexOf('--name');
const name = nameIdx !== -1 ? args[nameIdx + 1] : 'World';
const isShout = args.includes('--shout');
const isHelp = args.includes('--help') || args.includes('-h');
if (isHelp || !command) {
console.log('Usage: cli <command> [options]');
console.log('Commands:');
console.log(' greet --name <name> [--shout] Print a greeting');
console.log(' version Print version');
process.exit(0);
}
if (command === 'version') {
const pkg = require('./package.json');
console.log(pkg.version);
process.exit(0);
}
if (command === 'greet') {
let msg = `Hello, ${name}!`;
if (isShout) msg = msg.toUpperCase();
console.log(msg);
process.exit(0);
}
console.error(`Unknown command: ${command}`);
process.exit(1);
const readline = require('readline');
// Create a readline interface for interactive prompts
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// ANSI colors
const c = {
green: (s) => `\x1b[32m${s}\x1b[0m`,
red: (s) => `\x1b[31m${s}\x1b[0m`,
bold: (s) => `\x1b[1m${s}\x1b[0m`,
dim: (s) => `\x1b[2m${s}\x1b[0m`,
};
// Promisify rl.question (Node 17+ has a native .question Promise)
function ask(question) {
return new Promise(resolve => rl.question(question, resolve));
}
async function setup() {
console.log(c.bold('\nProject Setup Wizard'));
console.log(c.dim('Press Ctrl+C to cancel\n'));
const name = await ask('Project name: ');
const version = await ask('Version (1.0.0): ') || '1.0.0';
const author = await ask('Author: ');
rl.close();
const pkg = { name, version, author,
scripts: { start: 'node index.js' }, dependencies: {} };
console.log('\n' + c.bold('Generated package.json:'));
console.log(JSON.stringify(pkg, null, 2));
console.log('\n' + c.green('✓ Done!'));
}
setup().catch(err => {
console.error(c.red('\nError: ' + err.message));
process.exit(1);
});
Frequently Asked Questions
How do I make my Node.js script run as a global command (e.g., `mytool` instead of `node tool.js`)?
1. Add a shebang line at the top: `#!/usr/bin/env node`. 2. Make it executable: `chmod +x cli.js` (on Mac/Linux). 3. Add to package.json: `"bin": { "mytool": "./cli.js" }`. 4. Run `npm install -g .` (installs globally from the current directory). Now `mytool` runs your script. For sharing, publish to npm — `npm install -g your-package` makes it available globally.