The complete solution for Node.js command-line interfaces
npx @tessl/cli install tessl/npm-commander@14.0.0Commander.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.
npm install commanderimport { 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');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();Commander.js is built around several key components:
Command class providing the core command functionality with support for nested subcommandsOption class handling command-line flags and their values with extensive validation and configurationArgument class managing positional command arguments with type validation and processingHelp class providing comprehensive help text generation with extensive customization optionsCore 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;
}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;
}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;
}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;
}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;
}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;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;// 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';