कमांड-लाइन उपकरण दोहराए जाने वाले कार्यों, मचान परियोजनाओं और पावर डेवलपर वर्कफ़्लो को स्वचालित करते हैं। Node.js सीएलआई के निर्माण के लिए उत्कृष्ट है – परिचित जावास्क्रिप्ट, एक समृद्ध पारिस्थितिकी तंत्र और आसान एनपीएम वितरण। यह मार्गदर्शिका शुरुआत से ही एक संपूर्ण, प्रकाशन योग्य सीएलआई टूल बनाती है।
📋 Table of Contents
सीएलआई उपकरण क्यों बनाएं?
- स्वचालित वर्कफ़्लो: दोहराए जाने वाले कार्यों को एक ही कमांड में बदलें
- आसानी से वितरित करें: एनपीएम पर प्रकाशित करें, एक कमांड के साथ विश्व स्तर पर इंस्टॉल करें
- परिचित भाषा: एक विशाल पारिस्थितिकी तंत्र के साथ जावास्क्रिप्ट/टाइपस्क्रिप्ट
- क्रॉस-प्लेटफ़ॉर्म: Node.js कहीं भी चलता है
प्रोजेक्ट सेटअप
mkdir my-cli && cd my-cli
npm init -y
npm install commander chalk inquirer ora
// package.json - add the bin field and type
{
"name": "my-cli",
"version": "1.0.0",
"type": "module",
"bin": {
"mycli": "./index.js"
}
}
कमांडर के साथ बेसिक सीएलआई
#!/usr/bin/env node
// index.js - the shebang line makes it executable
import { program } from 'commander';
program
.name('mycli')
.description('A helpful developer CLI')
.version('1.0.0');
program
.command('greet')
.description('Greet someone')
.argument('', 'name to greet')
.option('-l, --loud', 'shout the greeting')
.action((name, options) => {
const msg = `Hello, ${name}!`;
console.log(options.loud ? msg.toUpperCase() : msg);
});
program.parse();
# Test it locally
node index.js greet Alice
# Hello, Alice!
node index.js greet Alice --loud
# HELLO, ALICE!
चाक के साथ रंगीन आउटपुट
import chalk from 'chalk';
console.log(chalk.green('✓ Success!'));
console.log(chalk.red('✗ Error occurred'));
console.log(chalk.yellow('⚠ Warning'));
console.log(chalk.blue.bold('Info:'), 'processing...');
// Combine styles
console.log(chalk.bgBlue.white(' TITLE '));
console.log(chalk.dim('subtle secondary text'));
पूछताछकर्ता के साथ इंटरएक्टिव संकेत
import inquirer from 'inquirer';
async function setup() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'projectName',
message: 'Project name?',
default: 'my-app',
},
{
type: 'list',
name: 'framework',
message: 'Choose a framework:',
choices: ['React', 'Vue', 'Svelte'],
},
{
type: 'confirm',
name: 'typescript',
message: 'Use TypeScript?',
default: true,
},
]);
console.log(chalk.green(`Creating ${answers.projectName} with ${answers.framework}...`));
return answers;
}
ओरा के साथ स्पिनर लोड हो रहे हैं
import ora from 'ora';
async function installDeps() {
const spinner = ora('Installing dependencies...').start();
try {
await runInstall(); // your async task
spinner.succeed('Dependencies installed');
} catch (err) {
spinner.fail('Installation failed');
throw err;
}
}
एक संपूर्ण उदाहरण: प्रोजेक्ट स्कैफ़ोल्डर
#!/usr/bin/env node
import { program } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import fs from 'fs/promises';
program
.command('create')
.description('Scaffold a new project')
.action(async () => {
const answers = await inquirer.prompt([
{ type: 'input', name: 'name', message: 'Project name?' },
{ type: 'list', name: 'template', message: 'Template?',
choices: ['api', 'web', 'cli'] },
]);
const spinner = ora('Creating project...').start();
try {
await fs.mkdir(answers.name, { recursive: true });
await fs.writeFile(
`${answers.name}/package.json`,
JSON.stringify({ name: answers.name, version: '0.1.0' }, null, 2)
);
spinner.succeed(chalk.green(`Created ${answers.name}!`));
console.log(chalk.dim(`\n cd ${answers.name}\n npm install\n`));
} catch (err) {
spinner.fail('Failed to create project');
console.error(err);
process.exit(1);
}
});
program.parse();
एनपीएम पर परीक्षण और प्रकाशन
# Link locally to test as a global command
npm link
mycli create # test it works globally
# Unlink when done testing
npm unlink -g my-cli
# Publish to npm
npm login
npm publish
# Users install it globally
npm install -g my-cli
mycli --help
सर्वोत्तम अभ्यास
- एक शेबंग जोड़ें (
#!/usr/bin/env node) इसलिए फ़ाइल एक निष्पादन योग्य - के रूप में चलती है सहायक–सहायता आउटपुट प्रदान करें – कमांडर इसे आपके विवरण से उत्पन्न करता है
- त्रुटियों को शालीनता से संभालें – विफलता पर गैर-शून्य कोड के साथ बाहर निकलें (
process.exit(1)) - स्पष्ट प्रतिक्रिया दें– स्पिनर, रंग, और सफलता/त्रुटि संदेश
- समर्थन –संस्करण– उपयोगकर्ता इसकी अपेक्षा करते हैं
- इनपुट मान्य करें– तर्कों की जांच करें और उपयोगी त्रुटियां दिखाएं
अक्सर पूछे जाने वाले प्रश्न
प्रश्न: तर्क पार्सिंग के लिए कमांडर या यार्ग?
ए: दोनों उत्कृष्ट हैं। कमांडर के पास एक साफ, श्रृंखलाबद्ध एपीआई है और यह बहुत लोकप्रिय है। यार्ग के साथ शक्तिशाली है more built-in features. For most CLIs, Commander is a great default. Try both and pick what feels natural.
Q: How do I make my CLI executable?
A: Add a shebang line (#!/usr/bin/env node) at the top of your entry file, and define the bin field in package.json mapping a command name to the file. After npm install -g (or npm link), the command is available globally.
Q: Should I use TypeScript for a CLI?
A: For larger CLIs, yes — type safety helps. Compile to JavaScript before publishing (or use a bundler like tsup). For small CLIs, plain JavaScript is simpler. TypeScript pays off as the tool grows.
Q: How do I handle configuration files?
A: Read config from a file (.myclirc, package.json field, or cosmiconfig which handles multiple formats). Let users configure defaults, then override with command-line flags. cosmiconfig is the standard library for this.
Q: Can I distribute a CLI without npm?
A: Yes — bundle it into a single executable with tools like pkg or Bun’s compile feature, producing a standalone binary users run without Node.js installed. Useful for wider distribution, though npm is simplest for developer audiences.
Conclusion
Building a CLI tool with Node.js is straightforward and rewarding. Use Commander for argument parsing, Chalk for colored output, Inquirer for interactive prompts, and Ora for spinners. Add a shebang line and a bin field in package.json to make it a global command, handle errors gracefully with proper exit codes, and provide clear feedback. Test locally with npm link, then publish to npm so anyone can install it with one command. CLI tools are one of the most practical things you can build — they automate आपके वर्कफ़्लो और प्रकाशित होने पर, अन्य डेवलपर्स को भी मदद मिलती है।
🔗 Share this article
✍️ Leave a Comment