Readme.md
This file
Path
Readme.md
1,146 lines · 41.2 KiB · Markdown
Last changed by
Add npm run-script to README (#1872)John Geebefore adoption60958df
History of this fileTake it
The walk stopped after 200 commits: lines older than b915706 point at it.
tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1–2why, one step back1# Commander.js2Drop travis and switch to GitHub Actions for build badge (#1393)John Geebefore adoption2f7aa33
line 3why, one step back3[](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 4–7why, one step back4[](https://www.npmjs.org/package/commander)5[](https://npmcharts.com/compare/commander?minimal=true)6[](https://packagephobia.now.sh/result?p=commander)7Merge branch 'develop' into release/7.xJohn Geebefore adoptiond90ef12
line 8why, one step back8The complete solution for [node.js](http://nodejs.org) command-line interfaces.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 9–13why, one step back910Read this in other languages: English | [简体中文](./Readme_zh-CN.md)1112- [Commander.js](#commanderjs)13 - [Installation](#installation)Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 14why, one step back14 - [Quick Start](#quick-start)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 15–18why, one step back15 - [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)Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 19why, one step back19 - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 20–22why, one step back20 - [Required option](#required-option)21 - [Variadic option](#variadic-option)22 - [Version option](#version-option)Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 23–24why, one step back23 - [More configuration](#more-configuration)24 - [Custom option processing](#custom-option-processing)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 25why, one step back25 - [Commands](#commands)Choices for arguments (#1525)John Geebefore adoption708527e
lines 26–28why, one step back26 - [Command-arguments](#command-arguments)27 - [More configuration](#more-configuration-1)28 - [Custom argument processing](#custom-argument-processing)Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 29why, one step back29 - [Action handler](#action-handler)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 30why, one step back30 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d
line 31why, one step back31 - [Life cycle hooks](#life-cycle-hooks)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 32–33why, one step back32 - [Automated help](#automated-help)33 - [Custom help](#custom-help)Add showHelpAfterError (#1534)John Geebefore adoption082717f
line 34why, one step back34 - [Display help after errors](#display-help-after-errors)Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
line 35why, one step back35 - [Display help from code](#display-help-from-code)Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 36–37why, one step back36 - [.name](#name)37 - [.usage](#usage)Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 38why, one step back38 - [.description and .summary](#description-and-summary)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 39–40why, one step back39 - [.helpOption(flags, description)](#helpoptionflags-description)40 - [.addHelpCommand()](#addhelpcommand)Choices for arguments (#1525)John Geebefore adoption708527e
line 41why, one step back41 - [More configuration](#more-configuration-2)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 42–44why, one step back42 - [Custom event listeners](#custom-event-listeners)43 - [Bits and pieces](#bits-and-pieces)44 - [.parse() and .parseAsync()](#parse-and-parseasync)Positional options (#1427)John Geebefore adoption8ac84ec
line 45why, one step back45 - [Parsing Configuration](#parsing-configuration)Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 46why, one step back46 - [Legacy options as properties](#legacy-options-as-properties)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 47–50why, one step back47 - [TypeScript](#typescript)48 - [createCommand()](#createcommand)49 - [Node options such as `--harmony`](#node-options-such-as---harmony)50 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)Add npm run-script to README (#1872)John Geebefore adoption60958df
line 51why, one step back51 - [npm run-script](#npm-run-script)Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 52why, one step back52 - [Display error](#display-error)configure output (#1387)John Geebefore adoptioned7f13e
line 53why, one step back53 - [Override exit and output handling](#override-exit-and-output-handling)Deprecated functionality (#1349)John Geebefore adoption9f5aabc
line 54why, one step back54 - [Additional documentation](#additional-documentation)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 55–57why, one step back55 - [Support](#support)56 - [Commander for enterprise](#commander-for-enterprise)57Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
lines 58–59why, one step back58For information about terms used in this document see: [terminology](./docs/terminology.md)59tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 60–61why, one step back60## Installation61Add Option.implies() (#1724)John Geebefore adoptiond660967
line 62why, one step back62```shtests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 63–65why, one step back63npm install commander64```65Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 66–90why, one step back66## Quick Start6768You write code to describe your command line interface.69Commander looks after parsing the arguments into options and command-arguments,70displays usage errors for problems, and implements a help system.7172Commander is strict and displays an error for unrecognised options.73The two most used option types are a boolean option, and an option which takes its value from the following argument.7475Example file: [split.js](./examples/split.js)7677```js78const { program } = require('commander');7980program81 .option('--first')82 .option('-s, --separator <char>');8384program.parse();8586const options = program.opts();87const limit = options.first ? 1 : undefined;88console.log(program.args[0].split(options.separator, limit));89```90Add Option.implies() (#1724)John Geebefore adoptiond660967
line 91why, one step back91```consoleMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 92–124why, one step back92$ node split.js -s / --fits a/b/c93error: unknown option '--fits'94(Did you mean --first?)95$ node split.js -s / --first a/b/c96[ 'a' ]97```9899Here 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).100101Example file: [string-util.js](./examples/string-util.js)102103```js104const { Command } = require('commander');105const program = new Command();106107program108 .name('string-util')109 .description('CLI to some JavaScript string utilities')110 .version('0.8.0');111112program.command('split')113 .description('Split a string into substrings and display as an array')114 .argument('<string>', 'string to split')115 .option('--first', 'display just the first substring')116 .option('-s, --separator <char>', 'separator character', ',')117 .action((str, options) => {118 const limit = options.first ? 1 : undefined;119 console.log(str.split(options.separator, limit));120 });121122program.parse();123```124Add Option.implies() (#1724)John Geebefore adoptiond660967
line 125why, one step back125```consoleMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 126–144why, one step back126$ node string-util.js help split127Usage: string-util split [options] <string>128129Split a string into substrings and display as an array.130131Arguments:132 string string to split133134Options:135 --first display just the first substring136 -s, --separator <char> separator character (default: ",")137 -h, --help display help for command138139$ node string-util.js split --separator=/ a/b/c140[ 'a', 'b', 'c' ]141```142143More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.144tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 145–150why, one step back145## Declaring _program_ variable146147Commander exports a global object which is convenient for quick programs.148This is used in the examples in this README for brevity.149150```jsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 151why, one step back151// CommonJS (.cjs)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 152–157why, one step back152const { program } = require('commander');153```154155For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.156157```jsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 158why, one step back158// CommonJS (.cjs)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 159–162why, one step back159const { Command } = require('commander');160const program = new Command();161```162Add support for named imports in ESM (#1440)John Geebefore adoption37825b3
line 163why, one step back163```jsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 164–165why, one step back164// ECMAScript (.mjs)165import { Command } from 'commander';Add support for named imports in ESM (#1440)John Geebefore adoption37825b3
lines 166–169why, one step back166const program = new Command();167```168169```tsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 170why, one step back170// TypeScript (.ts)Add support for named imports in ESM (#1440)John Geebefore adoption37825b3
lines 171–174why, one step back171import { Command } from 'commander';172const program = new Command();173```174tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 175–178why, one step back175## Options176177Options 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 or space or vertical bar ('|').178Add getOptionValue and setOptionValue (#1521)John Geebefore adoption6c06528
lines 179–181why, one step back179The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.180181Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 182why, one step back182Clarify option arguments (#1709)John Geebefore adoption7d7a674
line 183why, one step back183An 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.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 184why, one step back184Add Option.implies() (#1724)John Geebefore adoptiond660967
line 185why, one step back185```shClarify option arguments (#1709)John Geebefore adoption7d7a674
lines 186–191why, one step back186serve -p 80187serve -p80188serve --port 80189serve --port=80190```191tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 192–193why, one step back192You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.193Positional options (#1427)John Geebefore adoption8ac84ec
line 194why, one step back194By default options on the command line are not positional, and can be specified before or after other arguments.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 195why, one step back195Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 196–201why, one step back196There are additional related routines for when `.opts()` is not enough:197198- `.optsWithGlobals()` returns merged local and global option values199- `.getOptionValue()` and `.setOptionValue()` work with a single option value200- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from201tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 202–203why, one step back202### Common option types, boolean and value203Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 204why, one step back204The two most used option types are a boolean option, and an option which takes its valueUpdate Chinese docsWang Weixuanbefore adoptione6943c4
line 205why, one step back205from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 206–216why, one step back206207Example file: [options-common.js](./examples/options-common.js)208209```js210program211 .option('-d, --debug', 'output extra debugging')212 .option('-s, --small', 'small pizza size')213 .option('-p, --pizza-type <type>', 'flavour of pizza');214215program.parse(process.argv);216Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 217–218why, one step back217const options = program.opts();218if (options.debug) console.log(options);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 219why, one step back219console.log('pizza details:');Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 220–221why, one step back220if (options.small) console.log('- small pizza size');221if (options.pizzaType) console.log(`- ${options.pizzaType}`);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 222–223why, one step back222```223Add Option.implies() (#1724)John Geebefore adoptiond660967
line 224why, one step back224```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 225–226why, one step back225$ pizza-options -p226error: option '-p, --pizza-type <type>' argument missingRemove incorrect example output (#1532)John Geebefore adoptiond282f20
line 227why, one step back227$ pizza-options -d -s -p vegetariantests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 228–236why, one step back228{ debug: true, small: true, pizzaType: 'vegetarian' }229pizza details:230- small pizza size231- vegetarian232$ pizza-options --pizza-type=cheese233pizza details:234- cheese235```236Clarify option arguments (#1709)John Geebefore adoption7d7a674
lines 237–242why, one step back237Multiple boolean short options may be combined together following the dash, and may be followed by a single short option taking a value.238For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.239240Options with an expected option-argument are greedy and will consume the following argument whatever the value.241So `--id -xyz` reads `-xyz` as the option-argument.242Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 243why, one step back243`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`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 244–246why, one step back244245### Default option value246Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 247why, one step back247You can specify a default value for an option.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 248–254why, one step back248249Example file: [options-defaults.js](./examples/options-defaults.js)250251```js252program253 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');254Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 255why, one step back255program.parse();tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 256why, one step back256Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 257why, one step back257console.log(`cheese: ${program.opts().cheese}`);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 258–259why, one step back258```259Add Option.implies() (#1724)John Geebefore adoptiond660967
line 260why, one step back260```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 261–266why, one step back261$ pizza-options262cheese: blue263$ pizza-options --cheese stilton264cheese: stilton265```266Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 267why, one step back267### Other option types, negatable boolean and boolean|valuetests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 268why, one step back268Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 269why, one step back269You can define a boolean option long name with a leading `no-` to set the option value to false when used.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 270–272why, one step back270Defined alone this also makes the option true by default.271272If you define `--foo` first, adding `--no-foo` does not change the default value from what it wouldMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 273why, one step back273otherwise be.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 274–281why, one step back274275Example file: [options-negatable.js](./examples/options-negatable.js)276277```js278program279 .option('--no-sauce', 'Remove sauce')280 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')281 .option('--no-cheese', 'plain with no cheese')Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 282why, one step back282 .parse();tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 283why, one step back283Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 284–286why, one step back284const options = program.opts();285const sauceStr = options.sauce ? 'sauce' : 'no sauce';286const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 287–289why, one step back287console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);288```289Add Option.implies() (#1724)John Geebefore adoptiond660967
line 290why, one step back290```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 291–300why, one step back291$ pizza-options292You ordered a pizza with sauce and mozzarella cheese293$ pizza-options --sauce294error: unknown option '--sauce'295$ pizza-options --cheese=blue296You ordered a pizza with sauce and blue cheese297$ pizza-options --no-sauce --no-cheese298You ordered a pizza with no sauce and no cheese299```300Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
lines 301–302why, one step back301You can specify an option which may be used as a boolean option but may optionally take an option-argument302(declared with square brackets like `--optional [value]`).tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 303why, one step back303Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 304why, one step back304Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 305–311why, one step back305306```js307program308 .option('-c, --cheese [type]', 'Add cheese with optional type');309310program.parse(process.argv);311Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 312–315why, one step back312const options = program.opts();313if (options.cheese === undefined) console.log('no cheese');314else if (options.cheese === true) console.log('add cheese');315else console.log(`add cheese type ${options.cheese}`);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 316–317why, one step back316```317Add Option.implies() (#1724)John Geebefore adoptiond660967
line 318why, one step back318```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 319–324why, one step back319$ pizza-options320no cheese321$ pizza-options --cheese322add cheese323$ pizza-options --cheese mozzarella324add cheese type mozzarellaEnhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
line 325why, one step back325```Clarify option arguments (#1709)John Geebefore adoption7d7a674
lines 326–328why, one step back326327Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.328So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`.Enhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
line 329why, one step back329Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
lines 330–331why, one step back330For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).331Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
line 332why, one step back332### Required optionEnhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
line 333why, one step back333Add mention of makeOptionMandatory in README (#1797)John Geebefore adoption8236966
line 334why, one step back334You 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 (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 335–341why, one step back335336Example file: [options-required.js](./examples/options-required.js)337338```js339program340 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');341Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 342why, one step back342program.parse();Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 343–344why, one step back343```344Add Option.implies() (#1724)John Geebefore adoptiond660967
line 345why, one step back345```consoleRefactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 346–369why, one step back346$ pizza347error: required option '-c, --cheese <type>' not specified348```349350### Variadic option351352You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you353can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments354are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value355is specified in the same argument as the option then no further values are read.356357Example file: [options-variadic.js](./examples/options-variadic.js)358359```js360program361 .option('-n, --number <numbers...>', 'specify numbers')362 .option('-l, --letter [letters...]', 'specify letters');363364program.parse();365366console.log('Options: ', program.opts());367console.log('Remaining arguments: ', program.args);368```369Add Option.implies() (#1724)John Geebefore adoptiond660967
line 370why, one step back370```consoleRefactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 371–391why, one step back371$ collect -n 1 2 3 --letter a b c372Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }373Remaining arguments: []374$ collect --letter=A -n80 operand375Options: { number: [ '80' ], letter: [ 'A' ] }376Remaining arguments: [ 'operand' ]377$ collect --letter -n 1 -n 2 3 -- operand378Options: { number: [ '1', '2', '3' ], letter: true }379Remaining arguments: [ 'operand' ]380```381382For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).383384### Version option385386The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.387388```js389program.version('0.0.1');390```391Add Option.implies() (#1724)John Geebefore adoptiond660967
line 392why, one step back392```consoleRefactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 393–405why, one step back393$ ./examples/pizza -V3940.0.1395```396397You may change the flags and description by passing additional parameters to the `version` method, using398the same syntax for flags as the `option` method.399400```js401program.version('0.0.1', '-v, --vers', 'output the current version');402```403404### More configuration405Enhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
lines 406–408why, one step back406You can add most options using the `.option()` method, but there are some additional features available407by constructing an `Option` explicitly for less common cases.408Add Option.implies() (#1724)John Geebefore adoptiond660967
line 409why, one step back409Example 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)Enhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
lines 410–414why, one step back410411```js412program413 .addOption(new Option('-s, --secret').hideHelp())414 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 415why, one step back415 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 416why, one step back416 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 417why, one step back417 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 418–419why, one step back418 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))419 .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));Enhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
lines 420–421why, one step back420```421Add Option.implies() (#1724)John Geebefore adoptiond660967
line 422why, one step back422```consoleEnhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
lines 423–428why, one step back423$ extra --help424Usage: help [options]425426Options:427 -t, --timeout <delay> timeout in seconds (default: one minute)428 -d, --drink <size> drink cup size (choices: "small", "medium", "large")Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 429why, one step back429 -p, --port <number> port number (env: PORT)Add Option.implies() (#1724)John Geebefore adoptiond660967
line 430why, one step back430 --donate [amount] optional donation in dollars (preset: "20")feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 431why, one step back431 --disable-server disables the serverAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 432why, one step back432 --free-drink small drink included freeEnhance Option class to allow hiding help, specifying choices, and change how default value displayed in help (#1331)John Geebefore adoptiona05a8bc
lines 433–435why, one step back433 -h, --help display help for command434435$ extra --drink hugeSupport custom error messages for option argument coercion failures (#1392)John Geebefore adoption689d7a0
line 436why, one step back436error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 437why, one step back437Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 438–439why, one step back438$ PORT=80 extra --donate --free-drink439Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 440–442why, one step back440441$ extra --disable-server --port 8000442error: option '--disable-server' cannot be used with option '-p, --port <number>'tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 443why, one step back443```Add mention of makeOptionMandatory in README (#1797)John Geebefore adoption8236966
lines 444–445why, one step back444445Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option).tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 446–448why, one step back446447### Custom option processing448Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
lines 449–450why, one step back449You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,450the user specified option-argument and the previous value for the option. It returns the new value for the option.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 451why, one step back451Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 452why, one step back452This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 453why, one step back453Merge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
line 454why, one step back454You can optionally specify the default/starting value for the option after the function parameter.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 455–459why, one step back455456Example file: [options-custom-processing.js](./examples/options-custom-processing.js)457458```js459function myParseInt(value, dummyPrevious) {Support custom error messages for option argument coercion failures (#1392)John Geebefore adoption689d7a0
lines 460–462why, one step back460 // parseInt takes a string and a radix461 const parsedValue = parseInt(value, 10);462 if (isNaN(parsedValue)) {Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
line 463why, one step back463 throw new commander.InvalidArgumentError('Not a number.');Support custom error messages for option argument coercion failures (#1392)John Geebefore adoption689d7a0
lines 464–465why, one step back464 }465 return parsedValue;tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 466–487why, one step back466}467468function increaseVerbosity(dummyValue, previous) {469 return previous + 1;470}471472function collect(value, previous) {473 return previous.concat([value]);474}475476function commaSeparatedList(value, dummyPrevious) {477 return value.split(',');478}479480program481 .option('-f, --float <number>', 'float argument', parseFloat)482 .option('-i, --integer <number>', 'integer argument', myParseInt)483 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)484 .option('-c, --collect <value>', 'repeatable value', collect, [])485 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)486;487Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 488why, one step back488program.parse();tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 489why, one step back489Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 490–495why, one step back490const options = program.opts();491if (options.float !== undefined) console.log(`float: ${options.float}`);492if (options.integer !== undefined) console.log(`integer: ${options.integer}`);493if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);494if (options.collect.length > 0) console.log(options.collect);495if (options.list !== undefined) console.log(options.list);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 496–497why, one step back496```497Add Option.implies() (#1724)John Geebefore adoptiond660967
line 498why, one step back498```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 499–514why, one step back499$ custom -f 1e2500float: 100501$ custom --integer 2502integer: 2503$ custom -v -v -v504verbose: 3505$ custom -c a -c b -c c506[ 'a', 'b', 'c' ]507$ custom --list x,y,z508[ 'x', 'y', 'z' ]509```510511## Commands512513You 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 (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).514More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 515why, one step back515In 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...`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 516–530why, one step back516517You can use `.addCommand()` to add an already configured subcommand to the program.518519For example:520521```js522// Command implemented using action handler (description is supplied separately to `.command`)523// Returns new command for configuring.524program525 .command('clone <source> [destination]')526 .description('clone a repository into a newly created directory')527 .action((source, destination) => {528 console.log('clone command called');529 });530More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 531why, one step back531// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 532–542why, one step back532// Returns `this` for adding more commands.533program534 .command('start <service>', 'start named service')535 .command('stop [service]', 'stop named service, or all if no name supplied');536537// Command prepared separately.538// Returns `this` for adding more commands.539program540 .addCommand(build.makeBuildCommand());541```542Update Chinese docsWang Weixuanbefore adoptione6943c4
line 543why, one step back543Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` willMerge branch 'develop' into release/7.xJohn Geebefore adoptione5512a4
lines 544–545why, one step back544remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other545subcommand is specified ([example](./examples/defaultCommand.js)).tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 546why, one step back546Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 547–548why, one step back547You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js))548Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40
lines 549–550why, one step back549For 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.550Choices for arguments (#1525)John Geebefore adoption708527e
line 551why, one step back551### Command-argumentstests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 552why, one step back552More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
lines 553–555why, one step back553For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This554is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands555you can instead use the following method.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 556why, one step back556Update Chinese docsWang Weixuanbefore adoptione6943c4
line 557why, one step back557To configure a command, you can use `.argument()` to specify each expected command-argument.More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 558why, one step back558You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
line 559why, one step back559You can specify a default value for an optional command-argument.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 560why, one step back560More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
lines 561–562why, one step back561Example file: [argument.js](./examples/argument.js)562tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 563–565why, one step back563```js564program565 .version('0.1.0')More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 566why, one step back566 .argument('<username>', 'user to login')Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
line 567why, one step back567 .argument('[password]', 'password for user, if required', 'no password given')Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 568–569why, one step back568 .action((username, password) => {569 console.log('username:', username);Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
line 570why, one step back570 console.log('password:', password);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 571–574why, one step back571 });572```573574 The last argument of a command can be variadic, and only the last argument. To make an argument variadic youMore consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 575why, one step back575 append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 576–579why, one step back576577```js578program579 .version('0.1.0')More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
lines 580–581why, one step back580 .command('rmdir')581 .argument('<dirs...>')Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 582–585why, one step back582 .action(function (dirs) {583 dirs.forEach((dir) => {584 console.log('rmdir %s', dir);585 });tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 586–588why, one step back586 });587```588More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 589why, one step back589There is a convenience method to add multiple arguments at once, but without descriptions:tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 590why, one step back590More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
lines 591–593why, one step back591```js592program593 .arguments('<username> <password>');Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
lines 594–595why, one step back594```595Choices for arguments (#1525)John Geebefore adoption708527e
lines 596–608why, one step back596#### More configuration597598There are some additional features available by constructing an `Argument` explicitly for less common cases.599600Example file: [arguments-extra.js](./examples/arguments-extra.js)601602```js603program604 .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))605 .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))606```607608#### Custom argument processingExtend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
line 609why, one step back609Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 610why, one step back610You may specify a function to do custom processing of command-arguments (like for option-arguments).Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
lines 611–612why, one step back611The callback function receives two parameters, the user specified command-argument and the previous value for the argument.612It returns the new value for the argument.Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 613–614why, one step back613614The processed argument values are passed to the action handler, and saved as `.processedArgs`.Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
lines 615–628why, one step back615616You can optionally specify the default/starting value for the argument after the function parameter.617618Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)619620```js621program622 .command('add')623 .argument('<first>', 'integer argument', myParseInt)624 .argument('[second]', 'integer argument', myParseInt, 1000)625 .action((first, second) => {626 console.log(`${first} + ${second} = ${first + second}`);627 })628;More consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
lines 629–630why, one step back629```630Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 631why, one step back631### Action handlertests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 632why, one step back632Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 633why, one step back633The action handler gets passed a parameter for each command-argument you declared, and two additional parametersUpdate Chinese docsWang Weixuanbefore adoptione6943c4
line 634why, one step back634which are the parsed options and the command object itself.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 635why, one step back635Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 636why, one step back636Example file: [thank.js](./examples/thank.js)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 637why, one step back637Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 638why, one step back638```jstests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 639why, one step back639programMore consistent way of adding command arguments (#1490)John Geebefore adoptionb286da9
line 640why, one step back640 .argument('<name>')Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 641–649why, one step back641 .option('-t, --title <honorific>', 'title to use before name')642 .option('-d, --debug', 'display some debugging')643 .action((name, options, command) => {644 if (options.debug) {645 console.error('Called %s with options %o', command.name(), options);646 }647 const title = options.title ? `${options.title} ` : '';648 console.log(`Thank-you ${title}${name}`);649 });tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 650–651why, one step back650```651Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 652–665why, one step back652If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).653654Example file: [action-this.js](./examples/action-this.js)655656```js657program658 .command('serve')659 .argument('<script>')660 .option('-p, --port <number>', 'port number', 80)661 .action(function() {662 console.error('Run script %s on port %s', this.args[0], this.opts().port);663 });664```665tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 666–678why, one step back666You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.667668```js669async function run() { /* code goes here */ }670671async function main() {672 program673 .command('run')674 .action(run);675 await program.parseAsync(process.argv);676}677```678Make new excess arguments error opt-in (#1429)John Geebefore adoptione2670f4
lines 679–680why, one step back679A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to680pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 681–684why, one step back681682### Stand-alone executable (sub)commands683684When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 685–687why, one step back685Commander 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`.686You may specify a custom name (and path) with the `executableFile` configuration option.687You may specify a custom search directory for subcommands with `.executableDir()`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 688–694why, one step back688689You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.690691Example file: [pm](./examples/pm)692693```js694programMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 695why, one step back695 .name('pm')tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 696–705why, one step back696 .version('0.1.0')697 .command('install [name]', 'install one or more packages')698 .command('search [query]', 'search with optional query')699 .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })700 .command('list', 'list packages installed', { isDefault: true });701702program.parse(process.argv);703```704705If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d
lines 706–728why, one step back706707### Life cycle hooks708709You can add callback hooks to a command for life cycle events.710711Example file: [hook.js](./examples/hook.js)712713```js714program715 .option('-t, --trace', 'display trace statements for commands')716 .hook('preAction', (thisCommand, actionCommand) => {717 if (thisCommand.opts().trace) {718 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);719 console.log('arguments: %O', actionCommand.args);720 console.log('options: %o', actionCommand.opts());721 }722 });723```724725The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.726727The supported events are:728feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 729–732why, one step back729| event name | when hook called | callback parameters |730| :-- | :-- | :-- |731| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |732| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 733why, one step back733Add new documentation to READMEJohn Geebefore adoption5fbf83a
lines 734–735why, one step back734For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).735tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 736–742why, one step back736## Automated help737738The help information is auto-generated based on the information commander already knows about your program. The default739help option is `-h,--help`.740741Example file: [pizza](./examples/pizza)742Add Option.implies() (#1724)John Geebefore adoptiond660967
line 743why, one step back743```consoletests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 744–746why, one step back744$ node ./examples/pizza --help745Usage: pizza [options]746Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
line 747why, one step back747An application for pizza orderingtests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 748–758why, one step back748749Options:750 -p, --peppers Add peppers751 -c, --cheese <type> Add the specified type of cheese (default: "marble")752 -C, --no-cheese You do not want any cheese753 -h, --help display help for command754```755756A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show757further help for the subcommand. These are effectively the same if the `shell` program has implicit help:758Add Option.implies() (#1724)John Geebefore adoptiond660967
line 759why, one step back759```shtests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 760–766why, one step back760shell help761shell --help762763shell help spawn764shell spawn --help765```766Describe help description wrappingJohn Geebefore adoption1aa5271
lines 767–768why, one step back767Long 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.)768tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 769–770why, one step back769### Custom help770Update Chinese docsWang Weixuanbefore adoptione6943c4
line 771why, one step back771You can add extra text to be displayed along with the built-in help.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 772–778why, one step back772773Example file: [custom-help](./examples/custom-help)774775```js776program777 .option('-f, --foo', 'enable some foo');778Expand help customisation with .addHelpText (#1296)John Geebefore adoptiond26a26d
lines 779–782why, one step back779program.addHelpText('after', `780781Example call:782 $ custom-help --help`);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 783–797why, one step back783```784785Yields the following help output:786787```Text788Usage: custom-help [options]789790Options:791 -f, --foo enable some foo792 -h, --help display help for command793794Example call:795 $ custom-help --help796```797Expand help customisation with .addHelpText (#1296)John Geebefore adoptiond26a26d
lines 798–804why, one step back798The positions in order displayed are:799800- `beforeAll`: add to the program for a global banner or header801- `before`: display extra information before built-in help802- `after`: display extra information after built-in help803- `afterAll`: add to the program for a global footer (epilog)804Update Chinese docsWang Weixuanbefore adoptione6943c4
line 805why, one step back805The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.Expand help customisation with .addHelpText (#1296)John Geebefore adoptiond26a26d
lines 806–810why, one step back806807The 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:808809- error: a boolean for whether the help is being displayed due to a usage error810- command: the Command which is displaying the helpAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 811–813why, one step back811812### Display help after errors813Update Chinese docsWang Weixuanbefore adoptione6943c4
line 814why, one step back814The default behaviour for usage errors is to just display a short error message.Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 815–822why, one step back815You can change the behaviour to show the full help or a custom help message after an error.816817```js818program.showHelpAfterError();819// or820program.showHelpAfterError('(add --help for additional information)');821```822Add Option.implies() (#1724)John Geebefore adoptiond660967
line 823why, one step back823```consoleAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 824–827why, one step back824$ pizza --unknown825error: unknown option '--unknown'826(add --help for additional information)827```Expand help customisation with .addHelpText (#1296)John Geebefore adoptiond26a26d
line 828why, one step back828Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 829–830why, one step back829The default behaviour is to suggest correct spelling after an error for an unknown command or option. You830can disable this.Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 831–832why, one step back831832```jsAdd optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 833why, one step back833program.showSuggestionAfterError(false);Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 834–835why, one step back834```835Add Option.implies() (#1724)John Geebefore adoptiond660967
line 836why, one step back836```consoleSuggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 837–841why, one step back837$ pizza --hepl838error: unknown option '--hepl'839(Did you mean --help?)840```841Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 842–849why, one step back842### Display help from code843844`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.845846`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.847848`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.849Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 850why, one step back850### .nametests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 851why, one step back851Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 852why, one step back852The command name appears in the help, and is also used for locating stand-alone executable subcommands.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 853why, one step back853Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 854–857why, one step back854You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will855fallback to using the script name from the full arguments passed into `.parse()`. However, the script name varies856depending on how your program is launched so you may wish to specify it explicitly.857tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 858why, one step back858```jsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 859–870why, one step back859program.name('pizza');860const pm = new Command('pm');861```862863Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,864then set the name using `.name()` or in the Command constructor.865866### .usage867868This allows you to customise the usage description in the first line of the help. Given:869870```jstests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 871–879why, one step back871program872 .name("my-command")873 .usage("[global options] command")874```875876The help will start with:877878```Text879Usage: my-command [global options] commandAdd optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 880–893why, one step back880```881882### .description and .summary883884The description appears in the help for the command. You can optionally supply a shorter885summary to use when listed as a subcommand of the program.886887```js888program889 .command("duplicate")890 .summary("make a copy")891 .description(`Make a copy of the current project.892This may require additional disk space.893 `);tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 894–897why, one step back894```895896### .helpOption(flags, description)897Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 898why, one step back898By 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.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 899–906why, one step back899900```js901program902 .helpOption('-e, --HELP', 'read more information');903```904905### .addHelpCommand()906Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
line 907why, one step back907A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 908–912why, one step back908909You can both turn on and customise the help command by supplying the name and description:910911```js912program.addHelpCommand('assist [command]', 'show assistance');Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 913–921why, one step back913```914915### More configuration916917The built-in help is formatted using the Help class.918You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.919920The data properties are:921Rename columns to helpWidth (#1396)John Geebefore adoptioneac4787
line 922why, one step back922- `helpWidth`: specify the wrap width, useful for unit testsRefactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 923–924why, one step back923- `sortSubcommands`: sort the subcommands alphabetically924- `sortOptions`: sort the options alphabeticallyMerge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
line 925why, one step back925- `showGlobalOptions`: show a section with the global options from the parent command(s)Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
line 926why, one step back926Link to Help class in configure-help.js and README.Raine Reverebefore adoptionee78d95
line 927why, one step back927You can override any method on the [Help](./lib/help.js) class. There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.Refactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 928–930why, one step back928929Example file: [configure-help.js](./examples/configure-help.js)930Update Chinese docsWang Weixuanbefore adoptione6943c4
line 931why, one step back931```jsRefactor help internals into separate interface/class (#1365)John Geebefore adoption19ae912
lines 932–935why, one step back932program.configureHelp({933 sortSubcommands: true,934 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.935});tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 936–943why, one step back936```937938## Custom event listeners939940You can execute custom actions by listening to command and option events.941942```js943program.on('option:verbose', function () {Update documentation for option event listeners (#1470)Alex Havermalebefore adoption4a4c1d5
line 944why, one step back944 process.env.VERBOSE = this.opts().verbose;tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 945–966why, one step back945});946```947948## Bits and pieces949950### .parse() and .parseAsync()951952The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.953954If the arguments follow different conventions than node you can pass a `from` option in the second parameter:955956- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that957- 'electron': `argv[1]` varies depending on whether the electron application is packaged958- 'user': all of the arguments from the user959960For example:961962```js963program.parse(process.argv); // Explicit, node conventions964program.parse(); // Implicit, and auto-detect electron965program.parse(['-f', 'filename'], { from: 'user' });966```Positional options (#1427)John Geebefore adoption8ac84ec
lines 967–976why, one step back967968### Parsing Configuration969970If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.971972By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use973an option for a different purpose in subcommands.974975Example file: [positional-options.js](./examples/positional-options.js)976Add missing word and expand wording for clarity (#1482)John Geebefore adoption26223d0
line 977why, one step back977With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:Positional options (#1427)John Geebefore adoption8ac84ec
lines 978–985why, one step back978979```sh980program -b subcommand981program subcommand -b982```983984By default options are recognised before and after command-arguments. To only process options that come985before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another programUpdate Chinese docsWang Weixuanbefore adoptione6943c4
line 986why, one step back986without needing to use `--` to end the option processing.Positional options (#1427)John Geebefore adoption8ac84ec
lines 987–990why, one step back987To use pass through options in a subcommand, the program needs to enable positional options.988989Example file: [pass-through-options.js](./examples/pass-through-options.js)990Add missing word and expand wording for clarity (#1482)John Geebefore adoption26223d0
line 991why, one step back991With 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:Positional options (#1427)John Geebefore adoption8ac84ec
lines 992–998why, one step back992993```sh994program --port=80 arg995program arg --port=80996```997998By 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.Make new excess arguments error opt-in (#1429)John Geebefore adoptione2670f4
lines 999–1001why, one step back9991000By default the argument processing does not display an error for more command-arguments than expected.1001To display an error for excess arguments, use`.allowExcessArguments(false)`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 1002why, one step back1002Update Chinese docsWang Weixuanbefore adoptione6943c4
line 1003why, one step back1003### Legacy options as propertiestests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 1004why, one step back1004Change to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 1005–1007why, one step back1005Before Commander 7, the option values were stored as properties on the command.1006This was convenient to code but the downside was possible clashes with1007existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1008–1010why, one step back10081009```js1010programChange to safe storage of options by default, and change action parameters (#1409)John Geebefore adoptionf76bc71
lines 1011–1016why, one step back1011 .storeOptionsAsProperties()1012 .option('-d, --debug')1013 .action((commandAndOptions) => {1014 if (commandAndOptions.debug) {1015 console.error(`Called ${commandAndOptions.name()}`);1016 }tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1017–1021why, one step back1017 });1018```10191020### TypeScript1021Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173
lines 1022–1030why, one step back1022extra-typings: There is an optional project to infer extra type information from the option and argument definitions.1023This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.1024See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more.10251026```1027import { Command } from '@commander-js/extra-typings';1028```10291030ts-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.tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 1031why, one step back1031Add Option.implies() (#1724)John Geebefore adoptiond660967
line 1032why, one step back1032```shtests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1033–1046why, one step back1033node -r ts-node/register pm.ts1034```10351036### createCommand()10371038This factory function creates a new command. It is exported and may be used instead of using `new`, like:10391040```js1041const { createCommand } = require('commander');1042const program = createCommand();1043```10441045`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally1046when creating subcommands using `.command()`, and you may override it toUse custom command example to show revert to Commander v6 behaviours (#1421)John Geebefore adoption75c2a63
line 1047why, one step back1047customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1048–1063why, one step back10481049### Node options such as `--harmony`10501051You can enable `--harmony` option in two ways:10521053- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)1054- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.10551056### Debugging stand-alone executable subcommands10571058An executable subcommand is launched as a separate child process.10591060If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,1061the inspector port is incremented by 1 for the spawned subcommand.10621063If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.Add npm run-script to README (#1872)John Geebefore adoption60958df
lines 1064–1074why, one step back10641065### npm run-script10661067By 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. Use1068 `--` to stop the npm option parsing and pass through all the arguments.10691070 The synopsis for [npm run-script](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:10711072```console1073npm run-script <command> [-- <args>]1074```tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 1075why, one step back1075Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1076–1087why, one step back1076### Display error10771078This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)10791080As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)1081and `code` (used with `CommanderError`).10821083```js1084program.error('Password must be longer than four characters');1085program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });1086```1087configure output (#1387)John Geebefore adoptioned7f13e
line 1088why, one step back1088### Override exit and output handlingtests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1089–1103why, one step back10891090By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override1091this behaviour and optionally supply a callback. The default override throws a `CommanderError`.10921093The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help1094is not affected by the override which is called after the display.10951096```js1097program.exitOverride();10981099try {1100 program.parse(process.argv);1101} catch (err) {1102 // custom processing...1103}configure output (#1387)John Geebefore adoptioned7f13e
lines 1104–1124why, one step back1104```11051106By default Commander is configured for a command-line application and writes to stdout and stderr.1107You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.11081109Example file: [configure-output.js](./examples/configure-output.js)11101111```js1112function errorColor(str) {1113 // Add ANSI escape codes to display text in red.1114 return `\x1b[31m${str}\x1b[0m`;1115}11161117program1118 .configureOutput({1119 // Visibly override write routines as example!1120 writeOut: (str) => process.stdout.write(`[OUT] ${str}`),1121 writeErr: (str) => process.stdout.write(`[ERR] ${str}`),1122 // Highlight errors in color.1123 outputError: (str, write) => write(errorColor(str))1124 });tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
line 1125why, one step back1125```Deprecated functionality (#1349)John Geebefore adoption9f5aabc
lines 1126–1132why, one step back11261127### Additional documentation11281129There is more information available about:11301131- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility1132- [options taking varying arguments](./docs/options-taking-varying-arguments.md)Add new documentation to READMEJohn Geebefore adoption5fbf83a
line 1133why, one step back1133- [parsing life cycle and hooks](./docs/parsing-and-hooks.md)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1134–1136why, one step back11341135## Support1136Update minimum version of node in README (#1815)John Geebefore adoptionc897329
line 1137why, one step back1137The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v14.Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1138why, one step back1138(For older versions of Node.js, use an older version of Commander.)tests: remove eslint-disable jest/no-test-callback (#1312)michgabefore adoptionb915706
lines 1139–1146why, one step back11391140The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.11411142### Commander for enterprise11431144Available as part of the Tidelift Subscription11451146The 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)