Patterns Commander.js

VérifiéPrudence

Patterns et templates pour Commander.js incluant classes Command, options, arguments et sous-commandes imbriquées pour construire des CLI Node.js robustes.

Spar Skills Guide Bot
DeveloppementIntermédiaire
11/03/2026
Claude CodeCursorWindsurfCopilotCodex
#cli#nodejs#commanderjs#typescript#cli-arguments

Recommandé pour

Synthèse automatique

Fournit des modèles et des exemples de patterns Commander.js pour construire des CLI Node.js en TypeScript, avec commandes, options, arguments et sous-commandes imbriquées.

Points forts

  • Couvre les cas d'usage courants : options avec valeurs par défaut et choix, arguments requis, optionnels et variadiques
  • Montre l'usage avancé de la classe Option (choices, argParser, makeOptionMandatory)
  • Inclut la hiérarchie de sous-commandes via des commandes imbriquées
  • Exemples TypeScript directement copiables dans un projet

Limites

  • Le contenu fourni est tronqué, certains exemples (analyse d'arguments personnalisée, gestion d'erreurs) sont incomplets
  • Se limite à Commander.js et ne compare pas avec d'autres frameworks CLI
  • Ne traite pas la publication npm ni la structure complète d'un projet
Quand l'utiliser

À utiliser lorsqu'on écrit ou modifie une CLI Node.js ou TypeScript basée sur Commander.js, notamment pour ajouter des options, des arguments ou des sous-commandes.

Quand l'éviter

À éviter si le projet utilise un autre framework CLI (yargs, oclif, cac) ou s'il s'agit d'un script shell sans dépendance Node.js.

Analyse de sécurité

Prudence
Score qualité84/100

The skill is a Commander.js documentation/reference guide with no destructive, exfiltration, or obfuscated instructions. It does allow powerful file-writing and shell tools for legitimate CLI development tasks, and it references shell scripts whose contents are not shown, so it warrants caution rather than a fully safe rating.

Points d'attention
  • •Declares Bash, Write, and Edit tools, allowing an agent to execute shell commands and modify workspace files; this is legitimate for CLI scaffolding/testing but is a meaningful execution surface.
  • •References helper scripts such as validate-commander-structure.sh and generate-command.sh, but their contents are not included in SKILL.md, so their behavior cannot be audited from the provided material.
Comment cette analyse est faite

Exemples

Scaffold a CLI with a deploy command
Using Commander.js in TypeScript, create a CLI named mycli with a 'deploy' command that takes an <environment> argument and options --env (default 'dev'), --force, and --verbose.
Nested config subcommands
Add a 'config' command group to my Commander.js CLI with 'get <key>', 'set <key> <value>', and 'list' subcommands.
Validated option with Option class
Use Commander.js's Option class to add a --mode option restricted to 'fast', 'safe', and 'rollback' with a default of 'safe' and make it mandatory.

name: Commander.js Patterns description: Commander.js CLI framework patterns including Command class, options, arguments, nested subcommands, and Option class usage. Use when building Node.js CLIs, implementing Commander.js commands, creating TypeScript CLI tools, adding command options/arguments, or when user mentions Commander.js, CLI commands, command options, or nested subcommands. allowed-tools: Read, Write, Bash, Edit

Commander.js Patterns Skill

Provides comprehensive Commander.js patterns, templates, and examples for building robust Node.js CLI applications with TypeScript support.

Overview

Commander.js is the complete solution for Node.js command-line interfaces. This skill provides battle-tested patterns for:

  • Command class instantiation and configuration
  • Options with flags, choices, and defaults
  • Arguments (required, optional, variadic)
  • Nested subcommands and command hierarchies
  • Option class with advanced validation
  • Action handlers and middleware
  • Error handling and validation

Instructions

Basic Command Setup

  1. Create program instance:

    import { Command } from 'commander';
    const program = new Command();
    
    program
      .name('mycli')
      .description('CLI description')
      .version('1.0.0');
    
  2. Add simple command:

    program
      .command('init')
      .description('Initialize project')
      .action(() => {
        // Command logic
      });
    
  3. Parse arguments:

    program.parse();
    

Command with Options

Use options for named flags with values:

program
  .command('deploy')
  .description('Deploy application')
  .option('-e, --env <environment>', 'target environment', 'dev')
  .option('-f, --force', 'force deployment', false)
  .option('-v, --verbose', 'verbose output')
  .action((options) => {
    console.log('Environment:', options.env);
    console.log('Force:', options.force);
    console.log('Verbose:', options.verbose);
  });

Command with Arguments

Use arguments for positional parameters:

program
  .command('deploy <environment>')
  .description('Deploy to environment')
  .argument('<environment>', 'target environment')
  .argument('[region]', 'optional region', 'us-east-1')
  .action((environment, region, options) => {
    console.log(`Deploying to ${environment} in ${region}`);
  });

Option Class Usage

For advanced option configuration:

import { Command, Option } from 'commander';

program
  .command('deploy')
  .addOption(
    new Option('-m, --mode <mode>', 'deployment mode')
      .choices(['fast', 'safe', 'rollback'])
      .default('safe')
      .makeOptionMandatory()
  )
  .addOption(
    new Option('-r, --replicas <count>', 'replica count')
      .argParser(parseInt)
      .default(3)
  )
  .action((options) => {
    console.log(`Mode: ${options.mode}, Replicas: ${options.replicas}`);
  });

Nested Subcommands

Create command hierarchies:

const config = program
  .command('config')
  .description('Manage configuration');

config
  .command('get <key>')
  .description('Get config value')
  .action((key) => {
    console.log(`Config ${key}:`, getConfig(key));
  });

config
  .command('set <key> <value>')
  .description('Set config value')
  .action((key, value) => {
    setConfig(key, value);
    console.log(`✓ Set ${key} = ${value}`);
  });

config
  .command('list')
  .description('List all config')
  .action(() => {
    console.log(getAllConfig());
  });

Variadic Arguments

Accept multiple values:

program
  .command('add <items...>')
  .description('Add multiple items')
  .action((items) => {
    console.log('Adding items:', items);
  });

// Usage: mycli add item1 item2 item3

Custom Argument Parsing

Transform argument values:

program
  .command('wait <delay>')
  .description('Wait for specified time')
  .argument('<delay>', 'delay in seconds', parseFloat)
  .action((delay) => {
    console.log(`Waiting ${delay} seconds...`);
  });

Global Options

Options available to all commands:

program
  .option('-c, --config <path>', 'config file path')
  .option('-v, --verbose', 'verbose output')
  .option('--no-color', 'disable colors');

program
  .command('deploy')
  .action((options, command) => {
    const globalOpts = command.parent?.opts();
    console.log('Config:', globalOpts?.config);
    console.log('Verbose:', globalOpts?.verbose);
  });

Error Handling

program
  .command('deploy <environment>')
  .action((environment) => {
    if (!['dev', 'staging', 'prod'].includes(environment)) {
      throw new Error(`Invalid environment: ${environment}`);
    }
    // Deploy logic
  });

program.exitOverride();
try {
  program.parse();
} catch (err) {
  console.error('Error:', err.message);
  process.exit(1);
}

Available Scripts

  • validate-commander-structure.sh: Validates Commander.js CLI structure and patterns
  • generate-command.sh: Scaffolds new command with options and arguments
  • generate-subcommand.sh: Creates nested subcommand structure
  • test-commander-cli.sh: Tests CLI commands with various inputs
  • extract-command-help.sh: Extracts help text from CLI for documentation

Templates

TypeScript Templates

  • basic-commander.ts: Minimal Commander.js setup
  • command-with-options.ts: Command with various option types
  • command-with-arguments.ts: Command with required/optional arguments
  • nested-subcommands.ts: Multi-level command hierarchy
  • option-class-advanced.ts: Advanced Option class usage
  • full-cli-example.ts: Complete CLI with all patterns
  • commander-with-inquirer.ts: Interactive prompts integration
  • commander-with-validation.ts: Input validation patterns

JavaScript Templates

  • basic-commander.js: ES modules Commander.js setup
  • commonjs-commander.js: CommonJS Commander.js setup

Configuration Templates

  • tsconfig.commander.json: TypeScript config for Commander.js projects
  • package.json.template: Package.json with Commander.js dependencies

Examples

  • basic-usage.md: Simple CLI with 2-3 commands
  • options-arguments-demo.md: Comprehensive options and arguments examples
  • nested-commands-demo.md: Building command hierarchies
  • advanced-option-class.md: Option class validation and parsing
  • interactive-cli.md: Combining Commander.js with Inquirer.js
  • error-handling-patterns.md: Robust error handling strategies
  • testing-commander-cli.md: Unit and integration testing patterns

Commander.js Key Concepts

Command Class

new Command()
  .name('cli-name')
  .description('CLI description')
  .version('1.0.0')
  .command('subcommand')

Option Types

  • Flag option: -v, --verbose (boolean)
  • Value option: -p, --port <port> (required value)
  • Optional value: -p, --port [port] (optional value)
  • Negatable: --no-color (inverse boolean)
  • Variadic: --files <files...> (multiple values)

Argument Types

  • Required: <name>
  • Optional: [name]
  • Variadic: <items...> or [items...]

Option Class Methods

  • .choices(['a', 'b', 'c']): Restrict to specific values
  • .default(value): Set default value
  • .argParser(fn): Custom parsing function
  • .makeOptionMandatory(): Require option
  • .conflicts(option): Mutually exclusive options
  • .implies(option): Implies another option
  • .env(name): Read from environment variable

Action Handler Signatures

// No arguments
.action(() => {})

// With options only
.action((options) => {})

// With arguments
.action((arg1, arg2, options) => {})

// With command reference
.action((options, command) => {})

Pattern Recipes

Pattern 1: Simple CLI with Subcommands

Use template: templates/basic-commander.ts

Pattern 2: CLI with Rich Options

Use template: templates/option-class-advanced.ts

Pattern 3: Interactive CLI

Use template: templates/commander-with-inquirer.ts

Pattern 4: CLI with Validation

Use template: templates/commander-with-validation.ts

Pattern 5: Multi-level Commands

Use template: templates/nested-subcommands.ts

Integration with Other Tools

With Inquirer.js (Interactive Prompts)

import inquirer from 'inquirer';

program
  .command('setup')
  .action(async () => {
    const answers = await inquirer.prompt([
      { type: 'input', name: 'name', message: 'Project name:' },
      { type: 'list', name: 'template', message: 'Template:', choices: ['basic', 'advanced'] }
    ]);
    // Use answers
  });

With Chalk (Colored Output)

import chalk from 'chalk';

program
  .command('deploy')
  .action(() => {
    console.log(chalk.green('✓ Deployment successful'));
    console.log(chalk.red('✗ Deployment failed'));
  });

With Ora (Spinners)

import ora from 'ora';

program
  .command('build')
  .action(async () => {
    const spinner = ora('Building...').start();
    await build();
    spinner.succeed('Build complete');
  });

Best Practices

  1. Use Option class for complex options: Provides better validation and type safety
  2. Keep action handlers thin: Delegate to separate functions
  3. Provide clear descriptions: Help users understand commands
  4. Set sensible defaults: Reduce required options
  5. Validate early: Check inputs before processing
  6. Handle errors gracefully: Provide helpful error messages
  7. Use TypeScript: Better type safety and IDE support
  8. Test thoroughly: Unit test commands and options
  9. Document examples: Show common usage patterns
  10. Version your CLI: Use semantic versioning

Common Patterns

Pattern: Config Command Group

const config = program.command('config');
config.command('get <key>').action(getConfig);
config.command('set <key> <value>').action(setConfig);
config.command('list').action(listConfig);
config.command('delete <key>').action(deleteConfig);

Pattern: CRUD Commands

program.command('create <name>').action(create);
program.command('read <id>').action(read);
program.command('update <id>').action(update);
program.command('delete <id>').action(deleteItem);
program.command('list').action(list);

Pattern: Deploy with Environments

program
  .command('deploy')
  .addOption(new Option('-e, --env <env>').choices(['dev', 'staging', 'prod']))
  .option('-f, --force', 'force deployment')
  .action(deploy);

Troubleshooting

Issue: Options not parsed

Solution: Ensure program.parse() is called

Issue: Arguments not received

Solution: Check action handler signature matches argument count

Issue: Subcommands not working

Solution: Verify subcommand is attached before parse()

Issue: TypeScript errors

Solution: Install @types/node and configure tsconfig

Issue: Help not showing

Solution: Commander.js auto-generates help from descriptions

Success Criteria

✅ Command structure follows Commander.js conventions ✅ Options and arguments properly typed ✅ Help text is clear and descriptive ✅ Error handling covers edge cases ✅ CLI tested with various inputs ✅ TypeScript compiles without errors ✅ Commands execute as expected

Related Skills

  • click-patterns - Python Click framework patterns
  • typer-patterns - Python Typer framework patterns
  • clap-patterns - Rust Clap framework patterns

Skill Type: Framework Patterns + Code Templates Language: TypeScript/JavaScript (Node.js) Framework: Commander.js v12+ Auto-invocation: Yes (via description matching)

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/commander-js-patterns-mmlj2oj8/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/commander-js-patterns-mmlj2oj8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/commander-js-patterns-mmlj2oj8/download' --output '.skill-downloads/commander-js-patterns-mmlj2oj8/SKILL.md.part' && mv '.skill-downloads/commander-js-patterns-mmlj2oj8/SKILL.md.part' '.skill-downloads/commander-js-patterns-mmlj2oj8/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Bash, Edit

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Le fichier ne fournit pas un en-tête name/description exploitable pour cette procédure native. Le téléchargement reste disponible pour lecture ; utilisez le mode manuel ci-dessous.

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/commander-js-patterns-mmlj2oj8/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires