Skip to content

Command

reference
2 min readUpdated

Kind: Class

Source: lib/command.js

Command represents a CLI command and manages its child-command hierarchy, inherited settings, help output, and error behavior. It creates commands and help instances, applies output configuration, and controls help or suggestion display after errors.

Extends: EventEmitter

Methods

MethodSignatureReturns
copyInheritedSettingscopyInheritedSettings(sourceCommand: undefined)void
_getCommandAndAncestors_getCommandAndAncestors()void
commandcommand(nameAndArgs: undefined, actionOptsOrExecDesc: undefined, execOpts: undefined)void
createCommandcreateCommand(name: undefined)void
createHelpcreateHelp()void
configureHelpconfigureHelp(configuration: undefined)void
configureOutputconfigureOutput(configuration: undefined)void
showHelpAfterErrorshowHelpAfterError(displayHelp: undefined)void
showSuggestionAfterErrorshowSuggestionAfterError(displaySuggestion: undefined)void
addCommandaddCommand(cmd: undefined, opts: undefined)void
createArgumentcreateArgument(name: undefined, description: undefined)void
argumentargument(name: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)void
argumentsarguments(names: undefined)void
addArgumentaddArgument(argument: undefined)void
helpCommandhelpCommand(enableOrNameAndArgs: undefined, description: undefined)void
addHelpCommandaddHelpCommand(helpCommand: undefined, deprecatedDescription: undefined)void
_getHelpCommand_getHelpCommand()void
hookhook(event: undefined, listener: undefined)void
exitOverrideexitOverride(fn: undefined)void
_exit_exit(exitCode: undefined, code: undefined, message: undefined)void
actionaction(fn: undefined)void
createOptioncreateOption(flags: undefined, description: undefined)void
_callParseArg_callParseArg(target: undefined, value: undefined, previous: undefined, invalidArgumentMessage: undefined)void
_registerOption_registerOption(option: undefined)void
_registerCommand_registerCommand(command: undefined)void
addOptionaddOption(option: undefined)void
_optionEx_optionEx(config: undefined, flags: undefined, description: undefined, fn: undefined, defaultValue: undefined)void
optionoption(flags: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)void
requiredOptionrequiredOption(flags: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)void
combineFlagAndOptionalValuecombineFlagAndOptionalValue(combine: undefined)void
allowUnknownOptionallowUnknownOption(allowUnknown: undefined)void
allowExcessArgumentsallowExcessArguments(allowExcess: undefined)void
enablePositionalOptionsenablePositionalOptions(positional: undefined)void
passThroughOptionspassThroughOptions(passThrough: undefined)void
_checkForBrokenPassThrough_checkForBrokenPassThrough()void
storeOptionsAsPropertiesstoreOptionsAsProperties(storeAsProperties: undefined)void
getOptionValuegetOptionValue(key: undefined)void
setOptionValuesetOptionValue(key: undefined, value: undefined)void
setOptionValueWithSourcesetOptionValueWithSource(key: undefined, value: undefined, source: undefined)void
getOptionValueSourcegetOptionValueSource(key: undefined)void
getOptionValueSourceWithGlobalsgetOptionValueSourceWithGlobals(key: undefined)void
_prepareUserArgs_prepareUserArgs(argv: undefined, parseOptions: undefined)void
parseparse(argv: undefined, parseOptions: undefined)void
parseAsyncparseAsync(argv: undefined, parseOptions: undefined)void
_prepareForParse_prepareForParse()void
saveStateBeforeParsesaveStateBeforeParse()void
restoreStateBeforeParserestoreStateBeforeParse()void
_checkForMissingExecutable_checkForMissingExecutable(executableFile: undefined, executableDir: undefined, subcommandName: undefined)void
_executeSubCommand_executeSubCommand(subcommand: undefined, args: undefined)void
_dispatchSubcommand_dispatchSubcommand(commandName: undefined, operands: undefined, unknown: undefined)void

Where it refuses work

  • Command stops the work with Error when !cmd._name.
  • Command stops the work with Error when previousArgument?.variadic.
  • Command stops the work with Error when argument.required && argument.defaultValue !== undefined && argument.parseArg === undefin….
  • Command stops the work with Error when !allowedValues.includes(event).
  • Command stops the work with Error when typeof flags === 'object' && flags instanceof Option — “To add an Option object use addOption() instead of option() or requiredOption()”.
  • Command stops the work with Error when this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions.

When something fails

  • Command handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1.

Diagram

mermaid
graph LR
  Command -->|command() / addCommand()| ChildCommand
  Command -->|createCommand()| NewCommand
  Command -->|createHelp()| Help
  Command -->|configureHelp()| HelpSettings
  Command -->|configureOutput()| OutputSettings
  Command -->|copyInheritedSettings()| InheritedSettings
  Command -->|showHelpAfterError()| ErrorHelp
  Command -->|showSuggestionAfterError()| ErrorSuggestion
  ChildCommand -->|_getCommandAndAncestors()| CommandHierarchy

Usage

js
import { Command } from 'commander';

const program = new Command();

program
  .name('tool')
  .description('Example command-line tool')
  .configureHelp({
    sortSubcommands: true,
  })
  .configureOutput({
    writeErr: (message) => process.stderr.write(message),
  })
  .showHelpAfterError()
  .showSuggestionAfterError();

program
  .command('serve')
  .description('Start the service')
  .action(() => {
    console.log('Service started');
  });

program.parse();

AI Coding Instructions

  • Add subcommands through command() or addCommand() so they are attached to the command hierarchy.
  • Override createCommand() when a subclass needs to create a custom command type for child commands.
  • Configure help and output behavior before adding child commands when child commands should inherit those settings.
  • Treat _getCommandAndAncestors() as an internal helper for hierarchy traversal; avoid calling it from application code.
  • Keep showHelpAfterError() and showSuggestionAfterError() aligned with configured output handlers so error messages reach the expected stream.

Relationships

  • IMPORTS → Argument
  • IMPORTS → humanReadableArgName
  • IMPORTS → CommanderError
  • IMPORTS → Help
  • IMPORTS → Option
  • IMPORTS → DualOptions
  • IMPORTS → suggestSimilar

Used by

1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (1)

  • programindex.js:7

Was this page helpful?

Download as PDF