Kind: Class
Source: lib/argument.js
Argument defines a positional argument for a Commander command. It stores argument metadata such as the name, default value, parser, allowed choices, and whether the argument is required or optional.
Methods
| Method | Signature | Returns |
|---|---|---|
name | name() | void |
_collectValue | _collectValue(value: undefined, previous: undefined) | void |
default | default(value: undefined, description: undefined) | void |
argParser | argParser(fn: undefined) | void |
choices | choices(values: undefined) | void |
argRequired | argRequired() | void |
argOptional | argOptional() | void |
Where it refuses work
Argumentstops the work withInvalidArgumentErrorwhen!this.argChoices.includes(arg).Argumentstops the work with an early return whenprevious === this.defaultValue || !Array.isArray(previous).Argumentstops the work with an early return whenthis.variadic.
Diagram
mermaidgraph LR Command[Command] --> Argument[Argument] Argument --> Name[name()] Argument --> Default[default()] Argument --> Parser[argParser()] Argument --> Choices[choices()] Argument --> Required[argRequired()] Argument --> Optional[argOptional()] Parser --> Action[Command action] Choices --> Action
Usage
jsimport { Argument, Command } from 'commander';
const mode = new Argument('mode')
.choices(['development', 'production'])
.argRequired();
const label = new Argument('label')
.default('local')
.argOptional();
const program = new Command();
program
.name('deploy')
.addArgument(mode)
.addArgument(label)
.action((selectedMode, selectedLabel) => {
console.log(`Deploying ${selectedLabel} in ${selectedMode} mode`);
});
program.parse();
AI Coding Instructions
- Create
Argumentinstances and register them with aCommandusingaddArgument(). - Use
argRequired()orargOptional()to set positional argument behavior when it is not defined by the argument syntax. - Use
choices()for fixed string values; it sets the argument parsing behavior for choice validation. - Use
argParser()when an argument needs value conversion or custom validation, and return the parsed value. - Treat
_collectValue()as internal behavior for collecting repeated values rather than calling it from command code.
Relationships
- IMPORTS →
InvalidArgumentError
Used by
2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (2)
program—index.js:7Command—lib/command.js:14
Was this page helpful?