or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arguments.mdcommands.mderrors.mdhelp.mdindex.mdoptions.md
tile.json

index.mddocs/

Commander.js

Commander.js is the complete solution for Node.js command-line interfaces. It provides developers with powerful tools for creating command-line applications, featuring automatic parsing of command-line arguments and options, built-in help generation, support for subcommands with nested command structures, flexible option types including boolean, value, variadic, and required options, command argument handling with validation, custom action handlers for command execution, and extensive configuration capabilities.

Package Information

  • Package Name: commander
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install commander

Core Imports

import { program, Command, Option, Argument, Help, CommanderError, InvalidArgumentError, createCommand, createOption, createArgument } from 'commander';

For CommonJS:

const { program, Command, Option, Argument, Help, CommanderError, InvalidArgumentError, createCommand, createOption, createArgument } = require('commander');

Basic Usage

import { program } from 'commander';

// Simple program with options and arguments
program
  .name('string-util')
  .description('CLI to some JavaScript string utilities')
  .version('0.8.0');

program.command('split')
  .description('Split a string into substrings and display as an array')
  .argument('<string>', 'string to split')
  .option('--first', 'display just the first substring')
  .option('-s, --separator <char>', 'separator character', ',')
  .action((str, options) => {
    const limit = options.first ? 1 : undefined;
    console.log(str.split(options.separator, limit));
  });

program.parse();

Architecture

Commander.js is built around several key components:

  • Command System: Command class providing the core command functionality with support for nested subcommands
  • Options Processing: Option class handling command-line flags and their values with extensive validation and configuration
  • Arguments Handling: Argument class managing positional command arguments with type validation and processing
  • Help System: Help class providing comprehensive help text generation with extensive customization options
  • Error Management: Specialized error classes for handling parsing and validation errors
  • Factory Functions: Convenient factory functions for creating commands, options, and arguments

Capabilities

Command Management

Core command functionality for creating CLI applications with subcommands, nested command structures, and action handlers.

// Pre-created program instance
const program: Command;

// Factory function for creating new commands
function createCommand(name?: string): Command;

// Command class for building CLI applications
class Command extends EventEmitter {
  constructor(name?: string);
  
  // Core properties
  args: string[];
  processedArgs: any[];
  rawArgs: string[];
  readonly commands: readonly Command[];
  readonly options: readonly Option[];
  readonly registeredArguments: readonly Argument[];
  parent: Command | null;
  
  // Core configuration
  name(): string;
  name(str: string): this;
  description(): string;
  description(str: string): this;
  version(): string | undefined;
  version(str: string, flags?: string, description?: string): this;
  
  // Command building
  command(nameAndArgs: string, opts?: CommandOptions): Command;
  command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;
  addCommand(cmd: Command, opts?: CommandOptions): this;
  createCommand(name?: string): Command;
  
  // Action handling
  action(fn: (...args: any[]) => void | Promise<void>): this;
  
  // Parsing
  parse(argv?: readonly string[], parseOptions?: ParseOptions): this;
  parseAsync(argv?: readonly string[], parseOptions?: ParseOptions): Promise<this>;
  parseOptions(argv: string[]): ParseOptionsResult;
  
  // Configuration and state management
  nameFromFilename(filename: string): this;
  copyInheritedSettings(sourceCommand: Command): this;
  saveStateBeforeParse(): void;
  restoreStateBeforeParse(): void;
  
  // Event handling (EventEmitter)
  on(event: string | symbol, listener: (...args: any[]) => void): this;
}

Command Management

Event System

Commander extends EventEmitter, providing comprehensive event handling for command lifecycle, option processing, and help generation.

// Event handling methods (inherited from EventEmitter)
interface Command extends EventEmitter {
  // Generic event listener
  on(event: string | symbol, listener: (...args: any[]) => void): this;
  
  // Help system events
  on(event: 'beforeAllHelp' | 'beforeHelp' | 'afterHelp' | 'afterAllHelp', 
     listener: (context: { error: boolean, command: Command }) => void): this;
  
  // Option events - triggered when options are processed
  on(event: `option:${string}`, listener: (value?: any) => void): this;
  
  // Environment variable option events
  on(event: `optionEnv:${string}`, listener: (value?: any) => void): this;
  
  // Command events - triggered when subcommands are executed
  on(event: `command:${string}`, 
     listener: (operands: string[], unknown: string[]) => void): this;
}

// Hook system for lifecycle events
type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';

interface Command {
  hook(event: HookEvent, 
       listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;
}

Options Management

Comprehensive option system supporting boolean options, value options, variadic options, required options, option validation, conflicts, and environment variable integration. Options are resolved using precedence order: CLI arguments → environment variables → configuration files → default values → implied values.

// Factory function for creating options
function createOption(flags: string, description?: string): Option;

// Option class for command-line flags
class Option {
  constructor(flags: string, description?: string);
  
  // Configuration
  default(value: unknown, description?: string): this;
  preset(arg: unknown): this;
  conflicts(names: string | string[]): this;
  implies(optionValues: OptionValues): this;
  env(name: string): this;
  argParser<T>(fn: (value: string, previous: T) => T): this;
  makeOptionMandatory(mandatory?: boolean): this;
  choices(values: readonly string[]): this;
  
  // Utility methods
  name(): string;
  attributeName(): string;
  isBoolean(): boolean;
}

Options Management

Arguments Management

Command argument system with support for required, optional, and variadic arguments, custom processing, validation, and choice restrictions.

// Factory function for creating arguments
function createArgument(name: string, description?: string): Argument;

// Argument class for positional command arguments
class Argument {
  constructor(arg: string, description?: string);
  
  // Configuration
  name(): string;
  default(value: unknown, description?: string): this;
  argParser<T>(fn: (value: string, previous: T) => T): this;
  choices(values: readonly string[]): this;
  argRequired(): this;
  argOptional(): this;
}

Arguments Management

Help System

Comprehensive help generation and customization system with support for custom formatting, output configuration, help text positioning, and extensive styling options.

// Help class for help text generation and formatting
class Help {
  constructor();
  
  // Configuration properties
  helpWidth?: number;
  sortSubcommands: boolean;
  sortOptions: boolean;
  showGlobalOptions: boolean;
  
  // Content methods
  visibleCommands(cmd: Command): Command[];
  visibleOptions(cmd: Command): Option[];
  formatHelp(cmd: Command, helper: Help): string;
}

// Help configuration on Command
interface Command {
  createHelp(): Help;
  configureHelp(configuration: HelpConfiguration): this;
  configureOutput(configuration: OutputConfiguration): this;
  helpOption(flags?: string | boolean, description?: string): this;
  helpCommand(nameAndArgs: string, description?: string): this;
  addHelpText(position: AddHelpTextPosition, text: string | Function): this;
}

Help System

Error Handling

Specialized error classes for handling command-line parsing errors, invalid arguments, and custom error scenarios with exit code management.

// Base error class for Commander errors
class CommanderError extends Error {
  constructor(exitCode: number, code: string, message: string);
  exitCode: number;
  code: string;
  nestedError?: string;
}

// Error for invalid arguments or option values
class InvalidArgumentError extends CommanderError {
  constructor(message: string);
}

// Deprecated alias
const InvalidOptionArgumentError = InvalidArgumentError;

Error Handling

Utility Functions

Standalone utility functions for advanced use cases and internal operations.

// Factory functions for creating objects (already covered above but included for completeness)
function createCommand(name?: string): Command;
function createOption(flags: string, description?: string): Option;
function createArgument(name: string, description?: string): Argument;

// Utility function for extracting readable names from arguments  
function humanReadableArgName(arg: Argument): string;

Types

// Core configuration interfaces
interface CommandOptions {
  hidden?: boolean;
  isDefault?: boolean;
}

interface ExecutableCommandOptions extends CommandOptions {
  executableFile?: string;
}

interface ParseOptions {
  from: 'node' | 'electron' | 'user';
}

interface ParseOptionsResult {
  operands: string[];
  unknown: string[];
}

interface HelpContext {
  error: boolean;
}

interface OutputConfiguration {
  writeOut?(str: string): void;
  writeErr?(str: string): void;
  outputError?(str: string, write: (str: string) => void): void;
  getOutHelpWidth?(): number;
  getErrHelpWidth?(): number;
  getOutHasColors?(): boolean;
  getErrHasColors?(): boolean;
  stripColor?(str: string): string;
}

// Type aliases
type OptionValues = Record<string, any>;
type OptionValueSource = 'default' | 'config' | 'env' | 'cli' | 'implied' | string | undefined;
type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';