Readme.md
This file
Path
Readme.md
1,172 lines · 42.2 KiB · Markdown
Last changed by
Update changelog and version and engine for prerelease (#2484)John Geebefore adoption3f00f5b
History of this fileTake it
1# Commander.js23[](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)4[](https://www.npmjs.org/package/commander)5[](https://npmcharts.com/compare/commander?minimal=true)6[](https://packagephobia.now.sh/result?p=commander)78The complete solution for [node.js](http://nodejs.org) command-line interfaces.910Read this in other languages: English | [简体中文](./Readme_zh-CN.md)1112- [Commander.js](#commanderjs)13 - [Installation](#installation)14 - [Quick Start](#quick-start)15 - [Declaring _program_ variable](#declaring-program-variable)16 - [Options](#options)17 - [Common option types, boolean and value](#common-option-types-boolean-and-value)18 - [Default option value](#default-option-value)19 - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)20 - [Required option](#required-option)21 - [Variadic option](#variadic-option)22 - [Version option](#version-option)23 - [More configuration](#more-configuration)24 - [Custom option processing](#custom-option-processing)25 - [Commands](#commands)26 - [Command-arguments](#command-arguments)27 - [More configuration](#more-configuration-1)28 - [Custom argument processing](#custom-argument-processing)29 - [Action handler](#action-handler)30 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)31 - [Life cycle hooks](#life-cycle-hooks)32 - [Automated help](#automated-help)33 - [Custom help](#custom-help)34 - [Display help after errors](#display-help-after-errors)35 - [Display help from code](#display-help-from-code)36 - [.name](#name)37 - [.usage](#usage)38 - [.description and .summary](#description-and-summary)39 - [.helpOption(flags, description)](#helpoptionflags-description)40 - [.helpCommand()](#helpcommand)41 - [Help Groups](#help-groups)42 - [More configuration](#more-configuration-2)43 - [Custom event listeners](#custom-event-listeners)44 - [Bits and pieces](#bits-and-pieces)45 - [.parse() and .parseAsync()](#parse-and-parseasync)46 - [Parsing Configuration](#parsing-configuration)47 - [Legacy options as properties](#legacy-options-as-properties)48 - [TypeScript](#typescript)49 - [createCommand()](#createcommand)50 - [Node options such as `--harmony`](#node-options-such-as---harmony)51 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)52 - [npm run-script](#npm-run-script)53 - [Display error](#display-error)54 - [Override exit and output handling](#override-exit-and-output-handling)55 - [Additional documentation](#additional-documentation)56 - [Support](#support)57 - [Commander for enterprise](#commander-for-enterprise)5859For information about terms used in this document see: [terminology](./docs/terminology.md)6061## Installation6263```sh64npm install commander65```6667## Quick Start6869You write code to describe your command line interface.70Commander looks after parsing the arguments into options and command-arguments,71displays usage errors for problems, and implements a help system.7273Commander is strict and displays an error for unrecognised options.74The two most used option types are a boolean option, and an option which takes its value from the following argument.7576Example file: [split.js](./examples/split.js)7778```js79import { program } from 'commander';8081program82 .option('--first')83 .option('-s, --separator <char>')84 .argument('<string>');8586program.parse();8788const options = program.opts();89const limit = options.first ? 1 : undefined;90console.log(program.args[0].split(options.separator, limit));91```9293```console94$ node split.js -s - --fits a-b-c95error: unknown option '--fits'96(Did you mean --first?)97$ node split.js -s - --first a-b-c98[ 'a' ]99```100101Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands).102103Example file: [string-util.js](./examples/string-util.js)104105```js106import { Command } from 'commander';107const program = new Command();108109program110 .name('string-util')111 .description('CLI to some JavaScript string utilities')112 .version('0.8.0');113114program.command('split')115 .description('Split a string into substrings and display as an array')116 .argument('<string>', 'string to split')117 .option('--first', 'display just the first substring')118 .option('-s, --separator <char>', 'separator character', ',')119 .action((str, options) => {120 const limit = options.first ? 1 : undefined;121 console.log(str.split(options.separator, limit));122 });123124program.parse();125```126127```console128$ node string-util.js help split129Usage: string-util split [options] <string>130131Split a string into substrings and display as an array.132133Arguments:134 string string to split135136Options:137 --first display just the first substring138 -s, --separator <char> separator character (default: ",")139 -h, --help display help for command140141$ node string-util.js split --separator=- a-b-c142[ 'a', 'b', 'c' ]143```144145More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.146147## Declaring _program_ variable148149Commander exports a global object which is convenient for quick programs.150This is used in some examples in this README for brevity.151152```js153import { program } from 'commander';154```155156For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.157158```js159// CommonJS (.cjs)160const { Command } = require('commander');161const program = new Command();162```163164```js165// ECMAScript (.mjs)166import { Command } from 'commander';167const program = new Command();168```169170```ts171// TypeScript (.ts)172import { Command } from 'commander';173const program = new Command();174```175176## Options177178Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma, a space, or a vertical bar (`|`). To allow a wider range of short-ish flags than just single characters, you may also have two long options.179180```js181program182 .option('-p, --port <number>', 'server port number')183 .option('--trace', 'add extra debugging output')184 .option('--ws, --workspace <name>', 'use a custom workspace')185```186187The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.188189Multi-word options like `--template-engine` are normalized to camelCase option names, resulting in properties such as `program.opts().templateEngine`.190191An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly, or follow an `=` for a long option.192193```sh194serve -p 80195serve -p80196serve --port 80197serve --port=80198```199200You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.201202By default, options on the command line are not positional, and can be specified before or after other arguments.203204There are additional related routines for when `.opts()` is not enough:205206- `.optsWithGlobals()` returns merged local and global option values207- `.getOptionValue()` and `.setOptionValue()` work with a single option value208- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from209210### Common option types, boolean and value211212The two most used option types are a boolean option, and an option which takes its value213from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.214215Example file: [options-common.js](./examples/options-common.js)216217```js218program219 .option('-d, --debug', 'output extra debugging')220 .option('-s, --small', 'small pizza size')221 .option('-p, --pizza-type <type>', 'flavour of pizza');222223program.parse(process.argv);224225const options = program.opts();226if (options.debug) console.log(options);227console.log('pizza details:');228if (options.small) console.log('- small pizza size');229if (options.pizzaType) console.log(`- ${options.pizzaType}`);230```231232```console233$ pizza-options -p234error: option '-p, --pizza-type <type>' argument missing235$ pizza-options -d -s -p vegetarian236{ debug: true, small: true, pizzaType: 'vegetarian' }237pizza details:238- small pizza size239- vegetarian240$ pizza-options --pizza-type=cheese241pizza details:242- cheese243```244245Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.246For example, `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.247248Options with an expected option-argument are greedy and will consume the following argument whatever the value.249So `--id -xyz` reads `-xyz` as the option-argument.250251`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.252253### Default option value254255You can specify a default value for an option.256257Example file: [options-defaults.js](./examples/options-defaults.js)258259```js260program261 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');262263program.parse();264265console.log(`cheese: ${program.opts().cheese}`);266```267268```console269$ pizza-options270cheese: blue271$ pizza-options --cheese stilton272cheese: stilton273```274275### Other option types, negatable boolean and boolean|value276277You can define a boolean option long name with a leading `no-` to set the option value to `false` when used.278Defined alone without a matching positive option, this also makes the option `true` by default.279280Example file: [options-negatable.js](./examples/options-negatable.js)281282```js283program284 .option('--no-sauce', 'Remove sauce')285 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')286 .option('--no-cheese', 'plain with no cheese')287 .parse();288289const options = program.opts();290const sauceStr = options.sauce ? 'sauce' : 'no sauce';291const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;292console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);293```294295```console296$ pizza-options297You ordered a pizza with sauce and mozzarella cheese298$ pizza-options --sauce299error: unknown option '--sauce'300$ pizza-options --cheese=blue301You ordered a pizza with sauce and blue cheese302$ pizza-options --no-sauce --no-cheese303You ordered a pizza with no sauce and no cheese304```305306You can specify an option which may be used as a boolean option but may optionally take an option-argument307(declared with square brackets, like `--optional [value]`).308309Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)310311```js312program313 .option('-c, --cheese [type]', 'Add cheese with optional type');314315program.parse(process.argv);316317const options = program.opts();318if (options.cheese === undefined) console.log('no cheese');319else if (options.cheese === true) console.log('add cheese');320else console.log(`add cheese type ${options.cheese}`);321```322323```console324$ pizza-options325no cheese326$ pizza-options --cheese327add cheese328$ pizza-options --cheese mozzarella329add cheese type mozzarella330```331332Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.333So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`.334Negative numbers are special and are accepted as an option-argument.335336For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).337338### Required option339340You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (e.g., from environment). 341342The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.343344Example file: [options-required.js](./examples/options-required.js)345346```js347program348 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');349350program.parse();351```352353```console354$ pizza355error: required option '-c, --cheese <type>' not specified356```357358### Variadic option359360You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you361can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments362are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value363is specified in the same argument as the option, then no further values are read.364365Example file: [options-variadic.js](./examples/options-variadic.js)366367```js368program369 .option('-n, --number <numbers...>', 'specify numbers')370 .option('-l, --letter [letters...]', 'specify letters');371372program.parse();373374console.log('Options: ', program.opts());375console.log('Remaining arguments: ', program.args);376```377378```console379$ collect -n 1 2 3 --letter a b c380Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }381Remaining arguments: []382$ collect --letter=A -n80 operand383Options: { number: [ '80' ], letter: [ 'A' ] }384Remaining arguments: [ 'operand' ]385$ collect --letter -n 1 -n 2 3 -- operand386Options: { number: [ '1', '2', '3' ], letter: true }387Remaining arguments: [ 'operand' ]388```389390For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).391392### Version option393394The optional `.version()` method adds handling for displaying the command version. The default option flags are `-V` and `--version`. When used, the command prints the version number and exits.395396```js397program.version('0.0.1');398```399400```console401$ ./examples/pizza -V4020.0.1403```404405You may change the flags and description by passing additional parameters to the `.version()` method, using406the same syntax for flags as the `.option()` method.407408```js409program.version('0.0.1', '-v, --vers', 'output the current version');410```411412### More configuration413414You can add most options using the `.option()` method, but there are some additional features available415by constructing an `Option` explicitly for less common cases.416417Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js)418419```js420program421 .addOption(new Option('-s, --secret').hideHelp())422 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))423 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))424 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))425 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))426 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))427 .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));428```429430```console431$ extra --help432Usage: help [options]433434Options:435 -t, --timeout <delay> timeout in seconds (default: one minute)436 -d, --drink <size> drink cup size (choices: "small", "medium", "large")437 -p, --port <number> port number (env: PORT)438 --donate [amount] optional donation in dollars (preset: "20")439 --disable-server disables the server440 --free-drink small drink included free441 -h, --help display help for command442443$ extra --drink huge444error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.445446$ PORT=80 extra --donate --free-drink447Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }448449$ extra --disable-server --port 8000450error: option '--disable-server' cannot be used with option '-p, --port <number>'451```452453Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [`.requiredOption()`](#required-option).454455### Custom option processing456457You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,458the user specified option-argument and the previous value for the option. It returns the new value for the option.459460This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.461462You can optionally specify the default/starting value for the option after the function parameter.463464Example file: [options-custom-processing.js](./examples/options-custom-processing.js)465466```js467function myParseInt(value, dummyPrevious) {468 // parseInt takes a string and a radix469 const parsedValue = parseInt(value, 10);470 if (isNaN(parsedValue)) {471 throw new commander.InvalidArgumentError('Not a number.');472 }473 return parsedValue;474}475476function increaseVerbosity(dummyValue, previous) {477 return previous + 1;478}479480function collect(value, previous) {481 return previous.concat([value]);482}483484function commaSeparatedList(value, dummyPrevious) {485 return value.split(',');486}487488program489 .option('-f, --float <number>', 'float argument', parseFloat)490 .option('-i, --integer <number>', 'integer argument', myParseInt)491 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)492 .option('-c, --collect <value>', 'repeatable value', collect, [])493 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)494;495496program.parse();497498const options = program.opts();499if (options.float !== undefined) console.log(`float: ${options.float}`);500if (options.integer !== undefined) console.log(`integer: ${options.integer}`);501if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);502if (options.collect.length > 0) console.log(options.collect);503if (options.list !== undefined) console.log(options.list);504```505506```console507$ custom -f 1e2508float: 100509$ custom --integer 2510integer: 2511$ custom -v -v -v512verbose: 3513$ custom -c a -c b -c c514[ 'a', 'b', 'c' ]515$ custom --list x,y,z516[ 'x', 'y', 'z' ]517```518519## Commands520521You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an `.action()` handler attached to the command; or as a stand-alone executable file. (More detail about this later.)522523Subcommands may be nested. Example file: [nestedCommands.js](./examples/nestedCommands.js).524525In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.526527You can use `.addCommand()` to add an already configured subcommand to the program.528529For example:530531```js532// Command implemented using action handler (description is supplied separately to `.command`)533// Returns new command for configuring.534program535 .command('clone <source> [destination]')536 .description('clone a repository into a newly created directory')537 .action((source, destination) => {538 console.log('clone command called');539 });540541// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.542// Returns `this` for adding more commands.543program544 .command('start <service>', 'start named service')545 .command('stop [service]', 'stop named service, or all if no name supplied');546547// Command prepared separately.548// Returns `this` for adding more commands.549program550 .addCommand(build.makeBuildCommand());551```552553Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will554remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other555subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)556557You can add alternative names for a command with `.alias()`. (Example file: [alias.cjs](./examples/alias.cjs).)558559`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.560561For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.562563### Command-arguments564565For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This566is the only method usable for subcommands implemented using a stand-alone executable.567568Alternatively, you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument.569You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.570You can specify a default value for an optional command-argument.571572Example file: [argument.js](./examples/argument.js)573574```js575program576 .version('0.1.0')577 .argument('<username>', 'user to login')578 .argument('[password]', 'password for user, if required', 'no password given')579 .action((username, password) => {580 console.log('username:', username);581 console.log('password:', password);582 });583```584585The last argument of a command can be variadic, and _only_ the last argument. To make an argument variadic, simply586append `...` to the argument name.587588A variadic argument is passed to the action handler as an array.589590```js591program592 .version('0.1.0')593 .command('rmdir')594 .argument('<dirs...>')595 .action(function (dirs) {596 dirs.forEach((dir) => {597 console.log('rmdir %s', dir);598 });599 });600```601602There is a convenience method to add multiple arguments at once, but without descriptions:603604```js605program606 .arguments('<username> <password>');607```608609#### More configuration610611There are some additional features available by constructing an `Argument` explicitly for less common cases.612613Example file: [arguments-extra.js](./examples/arguments-extra.js)614615```js616program617 .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))618 .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))619```620621#### Custom argument processing622623You may specify a function to do custom processing of command-arguments (like for option-arguments).624The callback function receives two parameters, the user specified command-argument and the previous value for the argument.625It returns the new value for the argument.626627The processed argument values are passed to the action handler, and saved as `.processedArgs`.628629You can optionally specify the default/starting value for the argument after the function parameter.630631Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)632633```js634program635 .command('add')636 .argument('<first>', 'integer argument', myParseInt)637 .argument('[second]', 'integer argument', myParseInt, 1000)638 .action((first, second) => {639 console.log(`${first} + ${second} = ${first + second}`);640 })641;642```643644### Action handler645646The action handler gets passed a parameter for each command-argument you declared, and two additional parameters647which are the parsed options and the command object itself.648649Example file: [thank.js](./examples/thank.js)650651```js652program653 .argument('<name>')654 .option('-t, --title <honorific>', 'title to use before name')655 .option('-d, --debug', 'display some debugging')656 .action((name, options, command) => {657 if (options.debug) {658 console.error('Called %s with options %o', command.name(), options);659 }660 const title = options.title ? `${options.title} ` : '';661 console.log(`Thank-you ${title}${name}`);662 });663```664665If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. If you use a function expression (but not an arrow function), the `this` keyword is set to the running command.666667Example file: [action-this.js](./examples/action-this.js)668669```js670program671 .command('serve')672 .argument('<script>')673 .option('-p, --port <number>', 'port number', 80)674 .action(function() {675 console.error('Run script %s on port %s', this.args[0], this.opts().port);676 });677```678679You may supply an `async` action handler, in which case you call `.parseAsync()` rather than `.parse()`.680681```js682async function run() { /* code goes here */ }683684async function main() {685 program686 .command('run')687 .action(run);688 await program.parseAsync(process.argv);689}690```691692A command's options and arguments on the command line are validated when the command is used. Any unknown options, missing arguments, or excess arguments will be reported as an error. 693694You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.695696### Stand-alone executable (sub)commands697698When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.699Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand` (like `pm-install` or `pm-search` in the example below). The search includes trying common file extensions, like `.js`.700You may specify a custom name (and path) with the `executableFile` configuration option.701You may specify a custom search directory for subcommands with `.executableDir()`.702703You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.704705Example file: [pm](./examples/pm)706707```js708program709 .name('pm')710 .version('0.1.0')711 .command('install [package-names...]', 'install one or more packages')712 .command('search [query]', 'search with optional query')713 .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })714 .command('list', 'list packages installed', { isDefault: true });715716program.parse(process.argv);717```718719If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.720721### Life cycle hooks722723You can add callback hooks to a command for life cycle events.724725Example file: [hook.js](./examples/hook.js)726727```js728program729 .option('-t, --trace', 'display trace statements for commands')730 .hook('preAction', (thisCommand, actionCommand) => {731 if (thisCommand.opts().trace) {732 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);733 console.log('arguments: %O', actionCommand.args);734 console.log('options: %o', actionCommand.opts());735 }736 });737```738739The callback hook can be `async`, in which case you call `.parseAsync()` rather than `.parse()`. You can add multiple hooks per event.740741The supported events are:742743| event name | when hook called | callback parameters |744| :-- | :-- | :-- |745| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |746| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |747748For an overview of the life cycle events, see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).749750## Automated help751752The help information is auto-generated based on the information commander already knows about your program. The default753help option is `-h,--help`.754755Example file: [pizza](./examples/pizza)756757```console758$ node ./examples/pizza --help759Usage: pizza [options]760761An application for pizza ordering762763Options:764 -p, --peppers Add peppers765 -c, --cheese <type> Add the specified type of cheese (default: "marble")766 -C, --no-cheese You do not want any cheese767 -h, --help display help for command768```769770A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show771further help for the subcommand. These are effectively the same if the `shell` program has implicit help:772773```sh774shell help775shell --help776777shell help spawn778shell spawn --help779```780781Long descriptions are wrapped to fit the available width. (However, a description that includes a line-break followed by whitespace is assumed to be pre-formatted and not wrapped.)782783### Custom help784785You can add extra text to be displayed along with the built-in help.786787Example file: [custom-help](./examples/custom-help)788789```js790program791 .option('-f, --foo', 'enable some foo');792793program.addHelpText('after', `794795Example call:796 $ custom-help --help`);797```798799Yields the following help output:800801```Text802Usage: custom-help [options]803804Options:805 -f, --foo enable some foo806 -h, --help display help for command807808Example call:809 $ custom-help --help810```811812The positions in order displayed are:813814- `beforeAll`: add to the program for a global banner or header815- `before`: display extra information before built-in help816- `after`: display extra information after built-in help817- `afterAll`: add to the program for a global footer (epilog)818819The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.820821The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:822823- `error`: a boolean for whether the help is being displayed due to a usage error824- `command`: the `Command` which is displaying the help825826### Display help after errors827828The default behaviour for usage errors is to just display a short error message.829You can change the behaviour to show the full help or a custom help message after an error.830831```js832program.showHelpAfterError();833// or834program.showHelpAfterError('(add --help for additional information)');835```836837```console838$ pizza --unknown839error: unknown option '--unknown'840(add --help for additional information)841```842843The default behaviour is to suggest correct spelling after an error for an unknown command or option. You844can disable this.845846```js847program.showSuggestionAfterError(false);848```849850```console851$ pizza --hepl852error: unknown option '--hepl'853(Did you mean --help?)854```855856### Display help from code857858`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.859860`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.861862`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.863864### .name865866The command name appears in the help, and is also used for locating stand-alone executable subcommands.867868You may specify the program name using `.name()` or in the `Command` constructor. For the program, Commander will869fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies870depending on how your program is launched, so you may wish to specify it explicitly.871872```js873program.name('pizza');874const pm = new Command('pm');875```876877Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,878then set the name using `.name()` or in the `Command` constructor.879880### .usage881882This allows you to customise the usage description in the first line of the help. Given:883884```js885program886 .name("my-command")887 .usage("[global options] command")888```889890The help will start with:891892```Text893Usage: my-command [global options] command894```895896### .description and .summary897898The description appears in the help for the command. You can optionally supply a shorter899summary to use when listed as a subcommand of the program.900901```js902program903 .command("duplicate")904 .summary("make a copy")905 .description(`Make a copy of the current project.906This may require additional disk space.907 `);908```909910### .helpOption(flags, description)911912By default, every command has a help option. You may change the default help flags and description. Pass `false` to disable the built-in help option.913914```js915program916 .helpOption('-e, --HELP', 'read more information');917```918919Alternatively, use `.addHelpOption()` to add an option you construct yourself.920921### .helpCommand()922923A help command is added by default if your command has subcommands. You can explicitly turn the implicit help command on or off with `.helpCommand(true)` and `.helpCommand(false)`.924925You can both turn on and customise the help command by supplying the name and description:926927```js928program.helpCommand('assist [command]', 'show assistance');929```930931Alternatively, use `.addHelpCommand()` to add a command you construct yourself.932933### Help Groups934935The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups936with different headings. 937938- The high-level way is to set the desired group heading while adding the options and commands, using `.optionsGroup()` and `.commandsGroup()`. 939- The low-level way is using `.helpGroup()` on an individual `Option` or `Command`.940941Example file: [help-groups.js](./examples/help-groups.js)942943### More configuration944945The built-in help is formatted using the `Help` class.946You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing `Help` using `.createHelp()` .947948Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `.styleTitle()`.949950For more detail and examples of changing the displayed text, color, and layout, see: [Help in Depth](./docs/help-in-depth.md).951952## Custom event listeners953954You can execute custom actions by listening to `command` and `option` events.955956```js957program.on('option:verbose', function () {958 process.env.VERBOSE = this.opts().verbose;959});960```961962## Bits and pieces963964### .parse() and .parseAsync()965966Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!967968Or, call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:969970- `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that971- `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged972- `'user'`: just user arguments973974For example:975976```js977program.parse(); // parse process.argv and auto-detect electron and special node flags978program.parse(process.argv); // assume argv[0] is app and argv[1] is script979program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]980```981982Use `.parseAsync()` instead of `.parse()` if any of your action handlers are async.983984### Parsing Configuration985986If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.987988By default, program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use989an option for a different purpose in subcommands.990991Example file: [positional-options.js](./examples/positional-options.js)992993With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:994995```sh996program -b subcommand997program subcommand -b998```9991000By default, options are recognised before and after command-arguments. To only process options that come1001before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program1002without needing to use `--` to end the option processing.1003To use pass through options in a subcommand, the program needs to enable positional options.10041005Example file: [pass-through-options.js](./examples/pass-through-options.js)10061007With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:10081009```sh1010program --port=80 arg1011program arg --port=801012```10131014By default, the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.10151016By default, the argument processing displays an error for more command-arguments than expected.1017To suppress the error for excess arguments, use `.allowExcessArguments()`.10181019### Legacy options as properties10201021Before Commander 7, the option values were stored as properties on the command.1022This was convenient to code, but the downside was possible clashes with1023existing properties of `Command`. 10241025You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.10261027```js1028program1029 .storeOptionsAsProperties()1030 .option('-d, --debug')1031 .action((commandAndOptions) => {1032 if (commandAndOptions.debug) {1033 console.error(`Called ${commandAndOptions.name()}`);1034 }1035 });1036```10371038### TypeScript10391040**extra-typings:** There is an optional project to infer extra type information from the option and argument definitions.1041This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.1042For more, see the repo: [commander-js/extra-typings](https://github.com/commander-js/extra-typings).10431044```ts1045import { Command } from '@commander-js/extra-typings';1046```10471048**ts-node:** If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly, e.g.:10491050```sh1051node -r ts-node/register pm.ts1052```10531054### createCommand()10551056This factory function creates a new command. It is exported and may be used instead of using `new`, like:10571058```js1059import { createCommand } from 'commander';1060const program = createCommand();1061```10621063`createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally1064when creating subcommands using `.command()`, and you may override it to1065customise the new subcommand. Example file: [custom-command-class.js](./examples/custom-command-class.js).10661067### Node options such as `--harmony`10681069You can enable `--harmony` option in two ways:10701071- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note: Windows does not support this pattern.)1072- Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.10731074### Debugging stand-alone executable subcommands10751076An executable subcommand is launched as a separate child process.10771078If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,1079the inspector port is incremented by 1 for the spawned subcommand.10801081If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your `launch.json` configuration.10821083### npm run-script10841085By default, when you call your program using `run-script`, `npm` will parse any options on the command-line and they will not reach your program. Use1086 `--` to stop the npm option parsing and pass through all the arguments.10871088 The synopsis for [`npm run-script`](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:10891090```console1091npm run-script <command> [-- <args>]1092```10931094### Display error10951096This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)10971098As well as the error message, you can optionally specify the `exitCode` (used with `process.exit()`)1099and `code` (used with `CommanderError`).11001101```js1102program.error('Password must be longer than four characters');1103program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });1104```11051106### Override exit and output handling11071108By default, Commander calls `process.exit()` when it detects errors, or after displaying the help or version. You can override1109this behaviour and optionally supply a callback. The default override throws a `CommanderError`.11101111The override callback is passed a `CommanderError` with the properties:1112- `exitCode`: number1113- `code`: string 1114- `message`: string11151116Commander expects the callback to terminate the normal program flow, and will call `process.exit()` if the callback returns.1117The normal display of error messages or version or help is not affected by the override, which is called after the display.11181119```js1120program.exitOverride();11211122try {1123 program.parse(process.argv);1124} catch (err) {1125 // custom processing...1126}1127```11281129By default, Commander is configured for a command-line application and writes to stdout and stderr.1130You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.11311132Example file: [configure-output.js](./examples/configure-output.js)11331134```js1135function errorColor(str) {1136 // Add ANSI escape codes to display text in red.1137 return `\x1b[31m${str}\x1b[0m`;1138}11391140program1141 .configureOutput({1142 // Visibly override write routines as example!1143 writeOut: (str) => process.stdout.write(`[OUT] ${str}`),1144 writeErr: (str) => process.stdout.write(`[ERR] ${str}`),1145 // Highlight errors in color.1146 outputError: (str, write) => write(errorColor(str))1147 });1148```11491150### Additional documentation11511152There is more information available about:11531154- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility1155- [Help in Depth](./docs/help-in-depth.md) configuring help output1156- [options taking varying arguments](./docs/options-in-depth.md)1157- [parsing life cycle and hooks](./docs/parsing-and-hooks.md)1158- [Release Policy](./docs/release-policy.md)11591160## Support11611162The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v22.12.0.11631164Older major versions of Commander receive security updates for 12 months. For more see: [Release Policy](./docs/release-policy.md).11651166The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.11671168### Commander for enterprise11691170Available as part of the Tidelift Subscription11711172The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)