🌐 Detecting your location…

كيفية إنشاء أداة CLI باستخدام Node.js في عام 2026: الدليل الكامل

⏱️4 min read  ·  663 words

تعمل أدوات سطر الأوامر على أتمتة المهام المتكررة والمشاريع الداعمة وسير عمل مطوري الطاقة. يعد Node.js ممتازًا لبناء واجهات سطر الأوامر (CLI) — جافا سكريبت المألوفة، ونظام بيئي غني، وتوزيع npm سهل. يبني هذا الدليل أداة CLI كاملة وقابلة للنشر من البداية.

لماذا نبني أدوات CLI؟

  • أتمتة سير العمل: تحويل المهام المتكررة إلى أمر واحد
  • التوزيع بسهولة: النشر على npm، والتثبيت عالميًا باستخدام أمر واحد
  • لغة مألوفة: JavaScript/TypeScript مع نظام بيئي ضخم
  • عبر الأنظمة الأساسية: يتم تشغيله في أي مكان تعمل فيه 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();

الاختبار والنشر إلى npm

# 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))
  • تقديم تعليقات واضحة– الدوارات والألوان ورسائل النجاح/الخطأ
  • الدعم –الإصدار– يتوقعه المستخدمون
  • التحقق من صحة الإدخال– التحقق من الوسائط وإظهار الأخطاء المفيدة

الأسئلة المتداولة

س: قائد أو يارجز لتحليل الوسيطة؟
ج: كلاهما ممتاز. القائد لديه نظيفة وقابلة للتسلسل API and is very popular. Yargs is powerful with 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 الذي يتعامل مع تنسيقات متعددة). اسمح للمستخدمين بتكوين الإعدادات الافتراضية، ثم تجاوزها باستخدام علامات سطر الأوامر. cosmiconfig هي المكتبة القياسية لهذا س: هل يمكنني توزيع واجهة سطر الأوامر (CLI) بدون npm؟ ج: نعم – قم بتجميعها في ملف واحد قابل للتنفيذ باستخدام أدوات مثل pkg أو ميزة الترجمة الخاصة بـ Bun، مما يؤدي إلى تشغيل مستخدمين ثنائيين مستقلين بدون تثبيت Node.js.

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 field in package.json to make it a global command, handle errors gracefully with proper exit codes, and provide clear feedback. Test locally with , then publish إلى npm حتى يتمكن أي شخص من تثبيته باستخدام أمر واحد، تعد أدوات CLI واحدة من أكثر الأشياء العملية التي يمكنك إنشاؤها – فهي تعمل على أتمتة سير العمل الخاص بك، وتساعد المطورين الآخرين أيضًا عند نشرها.bin, then publish إلى npm حتى يتمكن أي شخص من تثبيته باستخدام أمر واحد، تعد أدوات CLI واحدة من أكثر الأشياء العملية التي يمكنك إنشاؤها – فهي تعمل على أتمتة سير العمل الخاص بك، وتساعد المطورين الآخرين أيضًا عند نشرها.npm link, then publish إلى npm حتى يتمكن أي شخص من تثبيته باستخدام أمر واحد، تعد أدوات CLI واحدة من أكثر الأشياء العملية التي يمكنك إنشاؤها – فهي تعمل على أتمتة سير العمل الخاص بك، وتساعد المطورين الآخرين أيضًا عند نشرها.

MD Rafikul Islam

Written by

MD Rafikul Islam is a software developer and the editor of TechPulse. He writes about developer tooling, hardware, and the practical decisions that come up in day-to-day engineering work — which laptop to buy, which framework to commit to, why a build broke at 2am. He tests the tools he writes about and says plainly when something is not worth the money. Corrections and corrections requests are welcome at rony.yf25@gmail.com.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা