3bd2bfe754843831088e45d628712eeeaf7dc2abc672a236204c9cc927b43c39c614a859a717b4d40627c4a448d502f265ed17ba3849b05ac54ec97409822c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. # Commander.js
  2. [![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
  3. [![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
  4. [![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
  5. [![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
  6. The complete solution for [node.js](http://nodejs.org) command-line interfaces.
  7. Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
  8. - [Commander.js](#commanderjs)
  9. - [Installation](#installation)
  10. - [Quick Start](#quick-start)
  11. - [Declaring _program_ variable](#declaring-program-variable)
  12. - [Options](#options)
  13. - [Common option types, boolean and value](#common-option-types-boolean-and-value)
  14. - [Default option value](#default-option-value)
  15. - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
  16. - [Required option](#required-option)
  17. - [Variadic option](#variadic-option)
  18. - [Version option](#version-option)
  19. - [More configuration](#more-configuration)
  20. - [Custom option processing](#custom-option-processing)
  21. - [Commands](#commands)
  22. - [Command-arguments](#command-arguments)
  23. - [More configuration](#more-configuration-1)
  24. - [Custom argument processing](#custom-argument-processing)
  25. - [Action handler](#action-handler)
  26. - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
  27. - [Life cycle hooks](#life-cycle-hooks)
  28. - [Automated help](#automated-help)
  29. - [Custom help](#custom-help)
  30. - [Display help after errors](#display-help-after-errors)
  31. - [Display help from code](#display-help-from-code)
  32. - [.name](#name)
  33. - [.usage](#usage)
  34. - [.description and .summary](#description-and-summary)
  35. - [.helpOption(flags, description)](#helpoptionflags-description)
  36. - [.helpCommand()](#helpcommand)
  37. - [Help Groups](#help-groups)
  38. - [More configuration](#more-configuration-2)
  39. - [Custom event listeners](#custom-event-listeners)
  40. - [Bits and pieces](#bits-and-pieces)
  41. - [.parse() and .parseAsync()](#parse-and-parseasync)
  42. - [Parsing Configuration](#parsing-configuration)
  43. - [Legacy options as properties](#legacy-options-as-properties)
  44. - [TypeScript](#typescript)
  45. - [createCommand()](#createcommand)
  46. - [Node options such as `--harmony`](#node-options-such-as---harmony)
  47. - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
  48. - [npm run-script](#npm-run-script)
  49. - [Display error](#display-error)
  50. - [Override exit and output handling](#override-exit-and-output-handling)
  51. - [Additional documentation](#additional-documentation)
  52. - [Support](#support)
  53. - [Commander for enterprise](#commander-for-enterprise)
  54. For information about terms used in this document see: [terminology](./docs/terminology.md)
  55. ## Installation
  56. ```sh
  57. npm install commander
  58. ```
  59. ## Quick Start
  60. You write code to describe your command line interface.
  61. Commander looks after parsing the arguments into options and command-arguments,
  62. displays usage errors for problems, and implements a help system.
  63. Commander is strict and displays an error for unrecognised options.
  64. The two most used option types are a boolean option, and an option which takes its value from the following argument.
  65. Example file: [split.js](./examples/split.js)
  66. ```js
  67. const { program } = require('commander');
  68. program
  69. .option('--first')
  70. .option('-s, --separator <char>')
  71. .argument('<string>');
  72. program.parse();
  73. const options = program.opts();
  74. const limit = options.first ? 1 : undefined;
  75. console.log(program.args[0].split(options.separator, limit));
  76. ```
  77. ```console
  78. $ node split.js -s / --fits a/b/c
  79. error: unknown option '--fits'
  80. (Did you mean --first?)
  81. $ node split.js -s / --first a/b/c
  82. [ 'a' ]
  83. ```
  84. Here 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).
  85. Example file: [string-util.js](./examples/string-util.js)
  86. ```js
  87. const { Command } = require('commander');
  88. const program = new Command();
  89. program
  90. .name('string-util')
  91. .description('CLI to some JavaScript string utilities')
  92. .version('0.8.0');
  93. program.command('split')
  94. .description('Split a string into substrings and display as an array')
  95. .argument('<string>', 'string to split')
  96. .option('--first', 'display just the first substring')
  97. .option('-s, --separator <char>', 'separator character', ',')
  98. .action((str, options) => {
  99. const limit = options.first ? 1 : undefined;
  100. console.log(str.split(options.separator, limit));
  101. });
  102. program.parse();
  103. ```
  104. ```console
  105. $ node string-util.js help split
  106. Usage: string-util split [options] <string>
  107. Split a string into substrings and display as an array.
  108. Arguments:
  109. string string to split
  110. Options:
  111. --first display just the first substring
  112. -s, --separator <char> separator character (default: ",")
  113. -h, --help display help for command
  114. $ node string-util.js split --separator=/ a/b/c
  115. [ 'a', 'b', 'c' ]
  116. ```
  117. More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
  118. ## Declaring _program_ variable
  119. Commander exports a global object which is convenient for quick programs.
  120. This is used in the examples in this README for brevity.
  121. ```js
  122. // CommonJS (.cjs)
  123. const { program } = require('commander');
  124. ```
  125. For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
  126. ```js
  127. // CommonJS (.cjs)
  128. const { Command } = require('commander');
  129. const program = new Command();
  130. ```
  131. ```js
  132. // ECMAScript (.mjs)
  133. import { Command } from 'commander';
  134. const program = new Command();
  135. ```
  136. ```ts
  137. // TypeScript (.ts)
  138. import { Command } from 'commander';
  139. const program = new Command();
  140. ```
  141. ## Options
  142. Options 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 ('|'). To allow a wider range of short-ish flags than just
  143. single characters, you may also have two long options. Examples:
  144. ```js
  145. program
  146. .option('-p, --port <number>', 'server port number')
  147. .option('--trace', 'add extra debugging output')
  148. .option('--ws, --workspace <name>', 'use a custom workspace')
  149. ```
  150. The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
  151. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
  152. An 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.
  153. ```sh
  154. serve -p 80
  155. serve -p80
  156. serve --port 80
  157. serve --port=80
  158. ```
  159. You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
  160. By default, options on the command line are not positional, and can be specified before or after other arguments.
  161. There are additional related routines for when `.opts()` is not enough:
  162. - `.optsWithGlobals()` returns merged local and global option values
  163. - `.getOptionValue()` and `.setOptionValue()` work with a single option value
  164. - `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from
  165. ### Common option types, boolean and value
  166. The two most used option types are a boolean option, and an option which takes its value
  167. from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
  168. Example file: [options-common.js](./examples/options-common.js)
  169. ```js
  170. program
  171. .option('-d, --debug', 'output extra debugging')
  172. .option('-s, --small', 'small pizza size')
  173. .option('-p, --pizza-type <type>', 'flavour of pizza');
  174. program.parse(process.argv);
  175. const options = program.opts();
  176. if (options.debug) console.log(options);
  177. console.log('pizza details:');
  178. if (options.small) console.log('- small pizza size');
  179. if (options.pizzaType) console.log(`- ${options.pizzaType}`);
  180. ```
  181. ```console
  182. $ pizza-options -p
  183. error: option '-p, --pizza-type <type>' argument missing
  184. $ pizza-options -d -s -p vegetarian
  185. { debug: true, small: true, pizzaType: 'vegetarian' }
  186. pizza details:
  187. - small pizza size
  188. - vegetarian
  189. $ pizza-options --pizza-type=cheese
  190. pizza details:
  191. - cheese
  192. ```
  193. Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.
  194. For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.
  195. Options with an expected option-argument are greedy and will consume the following argument whatever the value.
  196. So `--id -xyz` reads `-xyz` as the option-argument.
  197. `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`.
  198. ### Default option value
  199. You can specify a default value for an option.
  200. Example file: [options-defaults.js](./examples/options-defaults.js)
  201. ```js
  202. program
  203. .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
  204. program.parse();
  205. console.log(`cheese: ${program.opts().cheese}`);
  206. ```
  207. ```console
  208. $ pizza-options
  209. cheese: blue
  210. $ pizza-options --cheese stilton
  211. cheese: stilton
  212. ```
  213. ### Other option types, negatable boolean and boolean|value
  214. You can define a boolean option long name with a leading `no-` to set the option value to false when used.
  215. Defined alone this also makes the option true by default.
  216. If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
  217. otherwise be.
  218. Example file: [options-negatable.js](./examples/options-negatable.js)
  219. ```js
  220. program
  221. .option('--no-sauce', 'Remove sauce')
  222. .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  223. .option('--no-cheese', 'plain with no cheese')
  224. .parse();
  225. const options = program.opts();
  226. const sauceStr = options.sauce ? 'sauce' : 'no sauce';
  227. const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
  228. console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
  229. ```
  230. ```console
  231. $ pizza-options
  232. You ordered a pizza with sauce and mozzarella cheese
  233. $ pizza-options --sauce
  234. error: unknown option '--sauce'
  235. $ pizza-options --cheese=blue
  236. You ordered a pizza with sauce and blue cheese
  237. $ pizza-options --no-sauce --no-cheese
  238. You ordered a pizza with no sauce and no cheese
  239. ```
  240. You can specify an option which may be used as a boolean option but may optionally take an option-argument
  241. (declared with square brackets like `--optional [value]`).
  242. Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
  243. ```js
  244. program
  245. .option('-c, --cheese [type]', 'Add cheese with optional type');
  246. program.parse(process.argv);
  247. const options = program.opts();
  248. if (options.cheese === undefined) console.log('no cheese');
  249. else if (options.cheese === true) console.log('add cheese');
  250. else console.log(`add cheese type ${options.cheese}`);
  251. ```
  252. ```console
  253. $ pizza-options
  254. no cheese
  255. $ pizza-options --cheese
  256. add cheese
  257. $ pizza-options --cheese mozzarella
  258. add cheese type mozzarella
  259. ```
  260. Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.
  261. So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`.
  262. Negative numbers are special and are accepted as an option-argument.
  263. For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).
  264. ### Required option
  265. You 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.
  266. Example file: [options-required.js](./examples/options-required.js)
  267. ```js
  268. program
  269. .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
  270. program.parse();
  271. ```
  272. ```console
  273. $ pizza
  274. error: required option '-c, --cheese <type>' not specified
  275. ```
  276. ### Variadic option
  277. You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
  278. can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
  279. are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
  280. is specified in the same argument as the option then no further values are read.
  281. Example file: [options-variadic.js](./examples/options-variadic.js)
  282. ```js
  283. program
  284. .option('-n, --number <numbers...>', 'specify numbers')
  285. .option('-l, --letter [letters...]', 'specify letters');
  286. program.parse();
  287. console.log('Options: ', program.opts());
  288. console.log('Remaining arguments: ', program.args);
  289. ```
  290. ```console
  291. $ collect -n 1 2 3 --letter a b c
  292. Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
  293. Remaining arguments: []
  294. $ collect --letter=A -n80 operand
  295. Options: { number: [ '80' ], letter: [ 'A' ] }
  296. Remaining arguments: [ 'operand' ]
  297. $ collect --letter -n 1 -n 2 3 -- operand
  298. Options: { number: [ '1', '2', '3' ], letter: true }
  299. Remaining arguments: [ 'operand' ]
  300. ```
  301. For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).
  302. ### Version option
  303. The 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.
  304. ```js
  305. program.version('0.0.1');
  306. ```
  307. ```console
  308. $ ./examples/pizza -V
  309. 0.0.1
  310. ```
  311. You may change the flags and description by passing additional parameters to the `version` method, using
  312. the same syntax for flags as the `option` method.
  313. ```js
  314. program.version('0.0.1', '-v, --vers', 'output the current version');
  315. ```
  316. ### More configuration
  317. You can add most options using the `.option()` method, but there are some additional features available
  318. by constructing an `Option` explicitly for less common cases.
  319. Example 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)
  320. ```js
  321. program
  322. .addOption(new Option('-s, --secret').hideHelp())
  323. .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
  324. .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
  325. .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))
  326. .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))
  327. .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))
  328. .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));
  329. ```
  330. ```console
  331. $ extra --help
  332. Usage: help [options]
  333. Options:
  334. -t, --timeout <delay> timeout in seconds (default: one minute)
  335. -d, --drink <size> drink cup size (choices: "small", "medium", "large")
  336. -p, --port <number> port number (env: PORT)
  337. --donate [amount] optional donation in dollars (preset: "20")
  338. --disable-server disables the server
  339. --free-drink small drink included free
  340. -h, --help display help for command
  341. $ extra --drink huge
  342. error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
  343. $ PORT=80 extra --donate --free-drink
  344. Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }
  345. $ extra --disable-server --port 8000
  346. error: option '--disable-server' cannot be used with option '-p, --port <number>'
  347. ```
  348. Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option).
  349. ### Custom option processing
  350. You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
  351. the user specified option-argument and the previous value for the option. It returns the new value for the option.
  352. This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
  353. You can optionally specify the default/starting value for the option after the function parameter.
  354. Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
  355. ```js
  356. function myParseInt(value, dummyPrevious) {
  357. // parseInt takes a string and a radix
  358. const parsedValue = parseInt(value, 10);
  359. if (isNaN(parsedValue)) {
  360. throw new commander.InvalidArgumentError('Not a number.');
  361. }
  362. return parsedValue;
  363. }
  364. function increaseVerbosity(dummyValue, previous) {
  365. return previous + 1;
  366. }
  367. function collect(value, previous) {
  368. return previous.concat([value]);
  369. }
  370. function commaSeparatedList(value, dummyPrevious) {
  371. return value.split(',');
  372. }
  373. program
  374. .option('-f, --float <number>', 'float argument', parseFloat)
  375. .option('-i, --integer <number>', 'integer argument', myParseInt)
  376. .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  377. .option('-c, --collect <value>', 'repeatable value', collect, [])
  378. .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
  379. ;
  380. program.parse();
  381. const options = program.opts();
  382. if (options.float !== undefined) console.log(`float: ${options.float}`);
  383. if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
  384. if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
  385. if (options.collect.length > 0) console.log(options.collect);
  386. if (options.list !== undefined) console.log(options.list);
  387. ```
  388. ```console
  389. $ custom -f 1e2
  390. float: 100
  391. $ custom --integer 2
  392. integer: 2
  393. $ custom -v -v -v
  394. verbose: 3
  395. $ custom -c a -c b -c c
  396. [ 'a', 'b', 'c' ]
  397. $ custom --list x,y,z
  398. [ 'x', 'y', 'z' ]
  399. ```
  400. ## Commands
  401. You 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)).
  402. In 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...`.
  403. You can use `.addCommand()` to add an already configured subcommand to the program.
  404. For example:
  405. ```js
  406. // Command implemented using action handler (description is supplied separately to `.command`)
  407. // Returns new command for configuring.
  408. program
  409. .command('clone <source> [destination]')
  410. .description('clone a repository into a newly created directory')
  411. .action((source, destination) => {
  412. console.log('clone command called');
  413. });
  414. // Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
  415. // Returns `this` for adding more commands.
  416. program
  417. .command('start <service>', 'start named service')
  418. .command('stop [service]', 'stop named service, or all if no name supplied');
  419. // Command prepared separately.
  420. // Returns `this` for adding more commands.
  421. program
  422. .addCommand(build.makeBuildCommand());
  423. ```
  424. Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
  425. remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
  426. subcommand is specified ([example](./examples/defaultCommand.js)).
  427. You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js))
  428. `.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.
  429. For 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.
  430. ### Command-arguments
  431. For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
  432. is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
  433. you can instead use the following method.
  434. To configure a command, you can use `.argument()` to specify each expected command-argument.
  435. You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
  436. You can specify a default value for an optional command-argument.
  437. Example file: [argument.js](./examples/argument.js)
  438. ```js
  439. program
  440. .version('0.1.0')
  441. .argument('<username>', 'user to login')
  442. .argument('[password]', 'password for user, if required', 'no password given')
  443. .action((username, password) => {
  444. console.log('username:', username);
  445. console.log('password:', password);
  446. });
  447. ```
  448. The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
  449. append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
  450. ```js
  451. program
  452. .version('0.1.0')
  453. .command('rmdir')
  454. .argument('<dirs...>')
  455. .action(function (dirs) {
  456. dirs.forEach((dir) => {
  457. console.log('rmdir %s', dir);
  458. });
  459. });
  460. ```
  461. There is a convenience method to add multiple arguments at once, but without descriptions:
  462. ```js
  463. program
  464. .arguments('<username> <password>');
  465. ```
  466. #### More configuration
  467. There are some additional features available by constructing an `Argument` explicitly for less common cases.
  468. Example file: [arguments-extra.js](./examples/arguments-extra.js)
  469. ```js
  470. program
  471. .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
  472. .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
  473. ```
  474. #### Custom argument processing
  475. You may specify a function to do custom processing of command-arguments (like for option-arguments).
  476. The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
  477. It returns the new value for the argument.
  478. The processed argument values are passed to the action handler, and saved as `.processedArgs`.
  479. You can optionally specify the default/starting value for the argument after the function parameter.
  480. Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)
  481. ```js
  482. program
  483. .command('add')
  484. .argument('<first>', 'integer argument', myParseInt)
  485. .argument('[second]', 'integer argument', myParseInt, 1000)
  486. .action((first, second) => {
  487. console.log(`${first} + ${second} = ${first + second}`);
  488. })
  489. ;
  490. ```
  491. ### Action handler
  492. The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
  493. which are the parsed options and the command object itself.
  494. Example file: [thank.js](./examples/thank.js)
  495. ```js
  496. program
  497. .argument('<name>')
  498. .option('-t, --title <honorific>', 'title to use before name')
  499. .option('-d, --debug', 'display some debugging')
  500. .action((name, options, command) => {
  501. if (options.debug) {
  502. console.error('Called %s with options %o', command.name(), options);
  503. }
  504. const title = options.title ? `${options.title} ` : '';
  505. console.log(`Thank-you ${title}${name}`);
  506. });
  507. ```
  508. If 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).
  509. Example file: [action-this.js](./examples/action-this.js)
  510. ```js
  511. program
  512. .command('serve')
  513. .argument('<script>')
  514. .option('-p, --port <number>', 'port number', 80)
  515. .action(function() {
  516. console.error('Run script %s on port %s', this.args[0], this.opts().port);
  517. });
  518. ```
  519. You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
  520. ```js
  521. async function run() { /* code goes here */ }
  522. async function main() {
  523. program
  524. .command('run')
  525. .action(run);
  526. await program.parseAsync(process.argv);
  527. }
  528. ```
  529. A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments or excess arguments will be reported as an error. You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.
  530. ### Stand-alone executable (sub)commands
  531. When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
  532. Commander 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`.
  533. You may specify a custom name (and path) with the `executableFile` configuration option.
  534. You may specify a custom search directory for subcommands with `.executableDir()`.
  535. You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
  536. Example file: [pm](./examples/pm)
  537. ```js
  538. program
  539. .name('pm')
  540. .version('0.1.0')
  541. .command('install [package-names...]', 'install one or more packages')
  542. .command('search [query]', 'search with optional query')
  543. .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
  544. .command('list', 'list packages installed', { isDefault: true });
  545. program.parse(process.argv);
  546. ```
  547. If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
  548. ### Life cycle hooks
  549. You can add callback hooks to a command for life cycle events.
  550. Example file: [hook.js](./examples/hook.js)
  551. ```js
  552. program
  553. .option('-t, --trace', 'display trace statements for commands')
  554. .hook('preAction', (thisCommand, actionCommand) => {
  555. if (thisCommand.opts().trace) {
  556. console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
  557. console.log('arguments: %O', actionCommand.args);
  558. console.log('options: %o', actionCommand.opts());
  559. }
  560. });
  561. ```
  562. The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
  563. The supported events are:
  564. | event name | when hook called | callback parameters |
  565. | :-- | :-- | :-- |
  566. | `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |
  567. | `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |
  568. For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).
  569. ## Automated help
  570. The help information is auto-generated based on the information commander already knows about your program. The default
  571. help option is `-h,--help`.
  572. Example file: [pizza](./examples/pizza)
  573. ```console
  574. $ node ./examples/pizza --help
  575. Usage: pizza [options]
  576. An application for pizza ordering
  577. Options:
  578. -p, --peppers Add peppers
  579. -c, --cheese <type> Add the specified type of cheese (default: "marble")
  580. -C, --no-cheese You do not want any cheese
  581. -h, --help display help for command
  582. ```
  583. A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
  584. further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
  585. ```sh
  586. shell help
  587. shell --help
  588. shell help spawn
  589. shell spawn --help
  590. ```
  591. Long 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.)
  592. ### Custom help
  593. You can add extra text to be displayed along with the built-in help.
  594. Example file: [custom-help](./examples/custom-help)
  595. ```js
  596. program
  597. .option('-f, --foo', 'enable some foo');
  598. program.addHelpText('after', `
  599. Example call:
  600. $ custom-help --help`);
  601. ```
  602. Yields the following help output:
  603. ```Text
  604. Usage: custom-help [options]
  605. Options:
  606. -f, --foo enable some foo
  607. -h, --help display help for command
  608. Example call:
  609. $ custom-help --help
  610. ```
  611. The positions in order displayed are:
  612. - `beforeAll`: add to the program for a global banner or header
  613. - `before`: display extra information before built-in help
  614. - `after`: display extra information after built-in help
  615. - `afterAll`: add to the program for a global footer (epilog)
  616. The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
  617. The 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:
  618. - error: a boolean for whether the help is being displayed due to a usage error
  619. - command: the Command which is displaying the help
  620. ### Display help after errors
  621. The default behaviour for usage errors is to just display a short error message.
  622. You can change the behaviour to show the full help or a custom help message after an error.
  623. ```js
  624. program.showHelpAfterError();
  625. // or
  626. program.showHelpAfterError('(add --help for additional information)');
  627. ```
  628. ```console
  629. $ pizza --unknown
  630. error: unknown option '--unknown'
  631. (add --help for additional information)
  632. ```
  633. The default behaviour is to suggest correct spelling after an error for an unknown command or option. You
  634. can disable this.
  635. ```js
  636. program.showSuggestionAfterError(false);
  637. ```
  638. ```console
  639. $ pizza --hepl
  640. error: unknown option '--hepl'
  641. (Did you mean --help?)
  642. ```
  643. ### Display help from code
  644. `.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
  645. `.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
  646. `.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
  647. ### .name
  648. The command name appears in the help, and is also used for locating stand-alone executable subcommands.
  649. You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will
  650. fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies
  651. depending on how your program is launched, so you may wish to specify it explicitly.
  652. ```js
  653. program.name('pizza');
  654. const pm = new Command('pm');
  655. ```
  656. Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,
  657. then set the name using `.name()` or in the Command constructor.
  658. ### .usage
  659. This allows you to customise the usage description in the first line of the help. Given:
  660. ```js
  661. program
  662. .name("my-command")
  663. .usage("[global options] command")
  664. ```
  665. The help will start with:
  666. ```Text
  667. Usage: my-command [global options] command
  668. ```
  669. ### .description and .summary
  670. The description appears in the help for the command. You can optionally supply a shorter
  671. summary to use when listed as a subcommand of the program.
  672. ```js
  673. program
  674. .command("duplicate")
  675. .summary("make a copy")
  676. .description(`Make a copy of the current project.
  677. This may require additional disk space.
  678. `);
  679. ```
  680. ### .helpOption(flags, description)
  681. By 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.
  682. ```js
  683. program
  684. .helpOption('-e, --HELP', 'read more information');
  685. ```
  686. (Or use `.addHelpOption()` to add an option you construct yourself.)
  687. ### .helpCommand()
  688. A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.helpCommand(true)` and `.helpCommand(false)`.
  689. You can both turn on and customise the help command by supplying the name and description:
  690. ```js
  691. program.helpCommand('assist [command]', 'show assistance');
  692. ```
  693. (Or use `.addHelpCommand()` to add a command you construct yourself.)
  694. ### Help Groups
  695. The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups
  696. with different headings. The high-level way is to set the desired group heading while adding the options and commands,
  697. using `.optionsGroup()` and `.commandsGroup()`. The low-level way is using `.helpGroup()` on an individual `Option` or `Command`
  698. Example file: [help-groups.js](./examples/help-groups.js)
  699. ### More configuration
  700. The built-in help is formatted using the Help class.
  701. You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing Help using `.createHelp()` .
  702. Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `styleTitle()`.
  703. For more detail and examples of changing the displayed text, color, and layout see [help in depth](./docs/help-in-depth.md).
  704. ## Custom event listeners
  705. You can execute custom actions by listening to command and option events.
  706. ```js
  707. program.on('option:verbose', function () {
  708. process.env.VERBOSE = this.opts().verbose;
  709. });
  710. ```
  711. ## Bits and pieces
  712. ### .parse() and .parseAsync()
  713. Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
  714. Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
  715. - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
  716. - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
  717. - `'user'`: just user arguments
  718. For example:
  719. ```js
  720. program.parse(); // parse process.argv and auto-detect electron and special node flags
  721. program.parse(process.argv); // assume argv[0] is app and argv[1] is script
  722. program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  723. ```
  724. Use parseAsync instead of parse if any of your action handlers are async.
  725. ### Parsing Configuration
  726. If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
  727. By default, program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
  728. an option for a different purpose in subcommands.
  729. Example file: [positional-options.js](./examples/positional-options.js)
  730. With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
  731. ```sh
  732. program -b subcommand
  733. program subcommand -b
  734. ```
  735. By default, options are recognised before and after command-arguments. To only process options that come
  736. before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
  737. without needing to use `--` to end the option processing.
  738. To use pass through options in a subcommand, the program needs to enable positional options.
  739. Example file: [pass-through-options.js](./examples/pass-through-options.js)
  740. With 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:
  741. ```sh
  742. program --port=80 arg
  743. program arg --port=80
  744. ```
  745. By 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.
  746. By default, the argument processing displays an error for more command-arguments than expected.
  747. To suppress the error for excess arguments, use`.allowExcessArguments()`.
  748. ### Legacy options as properties
  749. Before Commander 7, the option values were stored as properties on the command.
  750. This was convenient to code, but the downside was possible clashes with
  751. existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
  752. ```js
  753. program
  754. .storeOptionsAsProperties()
  755. .option('-d, --debug')
  756. .action((commandAndOptions) => {
  757. if (commandAndOptions.debug) {
  758. console.error(`Called ${commandAndOptions.name()}`);
  759. }
  760. });
  761. ```
  762. ### TypeScript
  763. extra-typings: There is an optional project to infer extra type information from the option and argument definitions.
  764. This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.
  765. See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more.
  766. ```
  767. import { Command } from '@commander-js/extra-typings';
  768. ```
  769. 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.
  770. ```sh
  771. node -r ts-node/register pm.ts
  772. ```
  773. ### createCommand()
  774. This factory function creates a new command. It is exported and may be used instead of using `new`, like:
  775. ```js
  776. const { createCommand } = require('commander');
  777. const program = createCommand();
  778. ```
  779. `createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
  780. when creating subcommands using `.command()`, and you may override it to
  781. customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
  782. ### Node options such as `--harmony`
  783. You can enable `--harmony` option in two ways:
  784. - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
  785. - Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.
  786. ### Debugging stand-alone executable subcommands
  787. An executable subcommand is launched as a separate child process.
  788. If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,
  789. the inspector port is incremented by 1 for the spawned subcommand.
  790. If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
  791. ### npm run-script
  792. By 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. Use
  793. `--` to stop the npm option parsing and pass through all the arguments.
  794. The synopsis for [npm run-script](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:
  795. ```console
  796. npm run-script <command> [-- <args>]
  797. ```
  798. ### Display error
  799. This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)
  800. As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)
  801. and `code` (used with `CommanderError`).
  802. ```js
  803. program.error('Password must be longer than four characters');
  804. program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });
  805. ```
  806. ### Override exit and output handling
  807. By default, Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
  808. this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
  809. The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`.
  810. Commander expects the callback to terminate the normal program flow, and will call `process.exit` if the callback returns.
  811. The normal display of error messages or version or help is not affected by the override which is called after the display.
  812. ```js
  813. program.exitOverride();
  814. try {
  815. program.parse(process.argv);
  816. } catch (err) {
  817. // custom processing...
  818. }
  819. ```
  820. By default, Commander is configured for a command-line application and writes to stdout and stderr.
  821. You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
  822. Example file: [configure-output.js](./examples/configure-output.js)
  823. ```js
  824. function errorColor(str) {
  825. // Add ANSI escape codes to display text in red.
  826. return `\x1b[31m${str}\x1b[0m`;
  827. }
  828. program
  829. .configureOutput({
  830. // Visibly override write routines as example!
  831. writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
  832. writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
  833. // Highlight errors in color.
  834. outputError: (str, write) => write(errorColor(str))
  835. });
  836. ```
  837. ### Additional documentation
  838. There is more information available about:
  839. - [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
  840. - [options taking varying arguments](./docs/options-in-depth.md)
  841. - [parsing life cycle and hooks](./docs/parsing-and-hooks.md)
  842. ## Support
  843. The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v20.
  844. (For older versions of Node.js, use an older version of Commander.)
  845. The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
  846. ### Commander for enterprise
  847. Available as part of the Tidelift Subscription
  848. The 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)