You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1015 lines
36 KiB

6 months ago
  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. - [Declaring _program_ variable](#declaring-program-variable)
  11. - [Options](#options)
  12. - [Common option types, boolean and value](#common-option-types-boolean-and-value)
  13. - [Default option value](#default-option-value)
  14. - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
  15. - [Required option](#required-option)
  16. - [Variadic option](#variadic-option)
  17. - [Version option](#version-option)
  18. - [More configuration](#more-configuration)
  19. - [Custom option processing](#custom-option-processing)
  20. - [Commands](#commands)
  21. - [Command-arguments](#command-arguments)
  22. - [More configuration](#more-configuration-1)
  23. - [Custom argument processing](#custom-argument-processing)
  24. - [Action handler](#action-handler)
  25. - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
  26. - [Life cycle hooks](#life-cycle-hooks)
  27. - [Automated help](#automated-help)
  28. - [Custom help](#custom-help)
  29. - [Display help after errors](#display-help-after-errors)
  30. - [Display help from code](#display-help-from-code)
  31. - [.usage and .name](#usage-and-name)
  32. - [.helpOption(flags, description)](#helpoptionflags-description)
  33. - [.addHelpCommand()](#addhelpcommand)
  34. - [More configuration](#more-configuration-2)
  35. - [Custom event listeners](#custom-event-listeners)
  36. - [Bits and pieces](#bits-and-pieces)
  37. - [.parse() and .parseAsync()](#parse-and-parseasync)
  38. - [Parsing Configuration](#parsing-configuration)
  39. - [Legacy options as properties](#legacy-options-as-properties)
  40. - [TypeScript](#typescript)
  41. - [createCommand()](#createcommand)
  42. - [Node options such as `--harmony`](#node-options-such-as---harmony)
  43. - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
  44. - [Override exit and output handling](#override-exit-and-output-handling)
  45. - [Additional documentation](#additional-documentation)
  46. - [Examples](#examples)
  47. - [Support](#support)
  48. - [Commander for enterprise](#commander-for-enterprise)
  49. For information about terms used in this document see: [terminology](./docs/terminology.md)
  50. ## Installation
  51. ```bash
  52. npm install commander
  53. ```
  54. ## Declaring _program_ variable
  55. Commander exports a global object which is convenient for quick programs.
  56. This is used in the examples in this README for brevity.
  57. ```js
  58. const { program } = require('commander');
  59. program.version('0.0.1');
  60. ```
  61. For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
  62. ```js
  63. const { Command } = require('commander');
  64. const program = new Command();
  65. program.version('0.0.1');
  66. ```
  67. For named imports in ECMAScript modules, import from `commander/esm.mjs`.
  68. ```js
  69. // index.mjs
  70. import { Command } from 'commander/esm.mjs';
  71. const program = new Command();
  72. ```
  73. And in TypeScript:
  74. ```ts
  75. // index.ts
  76. import { Command } from 'commander';
  77. const program = new Command();
  78. ```
  79. ## Options
  80. 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 ('|').
  81. The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
  82. (You can also use `.getOptionValue()` and `.setOptionValue()` to work with a single option value,
  83. and `.getOptionValueSource()` and `.setOptionValueWithSource()` when it matters where the option value came from.)
  84. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
  85. Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
  86. For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
  87. You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
  88. By default options on the command line are not positional, and can be specified before or after other arguments.
  89. ### Common option types, boolean and value
  90. The two most used option types are a boolean option, and an option which takes its value
  91. from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
  92. Example file: [options-common.js](./examples/options-common.js)
  93. ```js
  94. program
  95. .option('-d, --debug', 'output extra debugging')
  96. .option('-s, --small', 'small pizza size')
  97. .option('-p, --pizza-type <type>', 'flavour of pizza');
  98. program.parse(process.argv);
  99. const options = program.opts();
  100. if (options.debug) console.log(options);
  101. console.log('pizza details:');
  102. if (options.small) console.log('- small pizza size');
  103. if (options.pizzaType) console.log(`- ${options.pizzaType}`);
  104. ```
  105. ```bash
  106. $ pizza-options -p
  107. error: option '-p, --pizza-type <type>' argument missing
  108. $ pizza-options -d -s -p vegetarian
  109. { debug: true, small: true, pizzaType: 'vegetarian' }
  110. pizza details:
  111. - small pizza size
  112. - vegetarian
  113. $ pizza-options --pizza-type=cheese
  114. pizza details:
  115. - cheese
  116. ```
  117. `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`.
  118. ### Default option value
  119. You can specify a default value for an option which takes a value.
  120. Example file: [options-defaults.js](./examples/options-defaults.js)
  121. ```js
  122. program
  123. .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
  124. program.parse();
  125. console.log(`cheese: ${program.opts().cheese}`);
  126. ```
  127. ```bash
  128. $ pizza-options
  129. cheese: blue
  130. $ pizza-options --cheese stilton
  131. cheese: stilton
  132. ```
  133. ### Other option types, negatable boolean and boolean|value
  134. You can define a boolean option long name with a leading `no-` to set the option value to false when used.
  135. Defined alone this also makes the option true by default.
  136. If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
  137. otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line.
  138. Example file: [options-negatable.js](./examples/options-negatable.js)
  139. ```js
  140. program
  141. .option('--no-sauce', 'Remove sauce')
  142. .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  143. .option('--no-cheese', 'plain with no cheese')
  144. .parse();
  145. const options = program.opts();
  146. const sauceStr = options.sauce ? 'sauce' : 'no sauce';
  147. const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
  148. console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
  149. ```
  150. ```bash
  151. $ pizza-options
  152. You ordered a pizza with sauce and mozzarella cheese
  153. $ pizza-options --sauce
  154. error: unknown option '--sauce'
  155. $ pizza-options --cheese=blue
  156. You ordered a pizza with sauce and blue cheese
  157. $ pizza-options --no-sauce --no-cheese
  158. You ordered a pizza with no sauce and no cheese
  159. ```
  160. You can specify an option which may be used as a boolean option but may optionally take an option-argument
  161. (declared with square brackets like `--optional [value]`).
  162. Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
  163. ```js
  164. program
  165. .option('-c, --cheese [type]', 'Add cheese with optional type');
  166. program.parse(process.argv);
  167. const options = program.opts();
  168. if (options.cheese === undefined) console.log('no cheese');
  169. else if (options.cheese === true) console.log('add cheese');
  170. else console.log(`add cheese type ${options.cheese}`);
  171. ```
  172. ```bash
  173. $ pizza-options
  174. no cheese
  175. $ pizza-options --cheese
  176. add cheese
  177. $ pizza-options --cheese mozzarella
  178. add cheese type mozzarella
  179. ```
  180. For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
  181. ### Required option
  182. 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.
  183. Example file: [options-required.js](./examples/options-required.js)
  184. ```js
  185. program
  186. .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
  187. program.parse();
  188. ```
  189. ```bash
  190. $ pizza
  191. error: required option '-c, --cheese <type>' not specified
  192. ```
  193. ### Variadic option
  194. You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
  195. can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
  196. are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
  197. is specified in the same argument as the option then no further values are read.
  198. Example file: [options-variadic.js](./examples/options-variadic.js)
  199. ```js
  200. program
  201. .option('-n, --number <numbers...>', 'specify numbers')
  202. .option('-l, --letter [letters...]', 'specify letters');
  203. program.parse();
  204. console.log('Options: ', program.opts());
  205. console.log('Remaining arguments: ', program.args);
  206. ```
  207. ```bash
  208. $ collect -n 1 2 3 --letter a b c
  209. Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
  210. Remaining arguments: []
  211. $ collect --letter=A -n80 operand
  212. Options: { number: [ '80' ], letter: [ 'A' ] }
  213. Remaining arguments: [ 'operand' ]
  214. $ collect --letter -n 1 -n 2 3 -- operand
  215. Options: { number: [ '1', '2', '3' ], letter: true }
  216. Remaining arguments: [ 'operand' ]
  217. ```
  218. For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
  219. ### Version option
  220. 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.
  221. ```js
  222. program.version('0.0.1');
  223. ```
  224. ```bash
  225. $ ./examples/pizza -V
  226. 0.0.1
  227. ```
  228. You may change the flags and description by passing additional parameters to the `version` method, using
  229. the same syntax for flags as the `option` method.
  230. ```js
  231. program.version('0.0.1', '-v, --vers', 'output the current version');
  232. ```
  233. ### More configuration
  234. You can add most options using the `.option()` method, but there are some additional features available
  235. by constructing an `Option` explicitly for less common cases.
  236. Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js)
  237. ```js
  238. program
  239. .addOption(new Option('-s, --secret').hideHelp())
  240. .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
  241. .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
  242. .addOption(new Option('-p, --port <number>', 'port number').env('PORT'));
  243. ```
  244. ```bash
  245. $ extra --help
  246. Usage: help [options]
  247. Options:
  248. -t, --timeout <delay> timeout in seconds (default: one minute)
  249. -d, --drink <size> drink cup size (choices: "small", "medium", "large")
  250. -p, --port <number> port number (env: PORT)
  251. -h, --help display help for command
  252. $ extra --drink huge
  253. error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
  254. $ PORT=80 extra
  255. Options: { timeout: 60, port: '80' }
  256. ```
  257. ### Custom option processing
  258. You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
  259. the user specified option-argument and the previous value for the option. It returns the new value for the option.
  260. This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
  261. You can optionally specify the default/starting value for the option after the function parameter.
  262. Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
  263. ```js
  264. function myParseInt(value, dummyPrevious) {
  265. // parseInt takes a string and a radix
  266. const parsedValue = parseInt(value, 10);
  267. if (isNaN(parsedValue)) {
  268. throw new commander.InvalidArgumentError('Not a number.');
  269. }
  270. return parsedValue;
  271. }
  272. function increaseVerbosity(dummyValue, previous) {
  273. return previous + 1;
  274. }
  275. function collect(value, previous) {
  276. return previous.concat([value]);
  277. }
  278. function commaSeparatedList(value, dummyPrevious) {
  279. return value.split(',');
  280. }
  281. program
  282. .option('-f, --float <number>', 'float argument', parseFloat)
  283. .option('-i, --integer <number>', 'integer argument', myParseInt)
  284. .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  285. .option('-c, --collect <value>', 'repeatable value', collect, [])
  286. .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
  287. ;
  288. program.parse();
  289. const options = program.opts();
  290. if (options.float !== undefined) console.log(`float: ${options.float}`);
  291. if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
  292. if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
  293. if (options.collect.length > 0) console.log(options.collect);
  294. if (options.list !== undefined) console.log(options.list);
  295. ```
  296. ```bash
  297. $ custom -f 1e2
  298. float: 100
  299. $ custom --integer 2
  300. integer: 2
  301. $ custom -v -v -v
  302. verbose: 3
  303. $ custom -c a -c b -c c
  304. [ 'a', 'b', 'c' ]
  305. $ custom --list x,y,z
  306. [ 'x', 'y', 'z' ]
  307. ```
  308. ## Commands
  309. 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)).
  310. 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...`.
  311. You can use `.addCommand()` to add an already configured subcommand to the program.
  312. For example:
  313. ```js
  314. // Command implemented using action handler (description is supplied separately to `.command`)
  315. // Returns new command for configuring.
  316. program
  317. .command('clone <source> [destination]')
  318. .description('clone a repository into a newly created directory')
  319. .action((source, destination) => {
  320. console.log('clone command called');
  321. });
  322. // Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
  323. // Returns `this` for adding more commands.
  324. program
  325. .command('start <service>', 'start named service')
  326. .command('stop [service]', 'stop named service, or all if no name supplied');
  327. // Command prepared separately.
  328. // Returns `this` for adding more commands.
  329. program
  330. .addCommand(build.makeBuildCommand());
  331. ```
  332. Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
  333. remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
  334. subcommand is specified ([example](./examples/defaultCommand.js)).
  335. ### Command-arguments
  336. For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
  337. is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
  338. you can instead use the following method.
  339. To configure a command, you can use `.argument()` to specify each expected command-argument.
  340. You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
  341. You can specify a default value for an optional command-argument.
  342. Example file: [argument.js](./examples/argument.js)
  343. ```js
  344. program
  345. .version('0.1.0')
  346. .argument('<username>', 'user to login')
  347. .argument('[password]', 'password for user, if required', 'no password given')
  348. .action((username, password) => {
  349. console.log('username:', username);
  350. console.log('password:', password);
  351. });
  352. ```
  353. The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
  354. append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
  355. ```js
  356. program
  357. .version('0.1.0')
  358. .command('rmdir')
  359. .argument('<dirs...>')
  360. .action(function (dirs) {
  361. dirs.forEach((dir) => {
  362. console.log('rmdir %s', dir);
  363. });
  364. });
  365. ```
  366. There is a convenience method to add multiple arguments at once, but without descriptions:
  367. ```js
  368. program
  369. .arguments('<username> <password>');
  370. ```
  371. #### More configuration
  372. There are some additional features available by constructing an `Argument` explicitly for less common cases.
  373. Example file: [arguments-extra.js](./examples/arguments-extra.js)
  374. ```js
  375. program
  376. .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
  377. .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
  378. ```
  379. #### Custom argument processing
  380. You may specify a function to do custom processing of command-arguments (like for option-arguments).
  381. The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
  382. It returns the new value for the argument.
  383. The processed argument values are passed to the action handler, and saved as `.processedArgs`.
  384. You can optionally specify the default/starting value for the argument after the function parameter.
  385. Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)
  386. ```js
  387. program
  388. .command('add')
  389. .argument('<first>', 'integer argument', myParseInt)
  390. .argument('[second]', 'integer argument', myParseInt, 1000)
  391. .action((first, second) => {
  392. console.log(`${first} + ${second} = ${first + second}`);
  393. })
  394. ;
  395. ```
  396. ### Action handler
  397. The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
  398. which are the parsed options and the command object itself.
  399. Example file: [thank.js](./examples/thank.js)
  400. ```js
  401. program
  402. .argument('<name>')
  403. .option('-t, --title <honorific>', 'title to use before name')
  404. .option('-d, --debug', 'display some debugging')
  405. .action((name, options, command) => {
  406. if (options.debug) {
  407. console.error('Called %s with options %o', command.name(), options);
  408. }
  409. const title = options.title ? `${options.title} ` : '';
  410. console.log(`Thank-you ${title}${name}`);
  411. });
  412. ```
  413. You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
  414. ```js
  415. async function run() { /* code goes here */ }
  416. async function main() {
  417. program
  418. .command('run')
  419. .action(run);
  420. await program.parseAsync(process.argv);
  421. }
  422. ```
  423. A 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 to
  424. pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.
  425. ### Stand-alone executable (sub)commands
  426. When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
  427. Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
  428. You can specify a custom name with the `executableFile` configuration option.
  429. You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
  430. Example file: [pm](./examples/pm)
  431. ```js
  432. program
  433. .version('0.1.0')
  434. .command('install [name]', 'install one or more packages')
  435. .command('search [query]', 'search with optional query')
  436. .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
  437. .command('list', 'list packages installed', { isDefault: true });
  438. program.parse(process.argv);
  439. ```
  440. If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
  441. ### Life cycle hooks
  442. You can add callback hooks to a command for life cycle events.
  443. Example file: [hook.js](./examples/hook.js)
  444. ```js
  445. program
  446. .option('-t, --trace', 'display trace statements for commands')
  447. .hook('preAction', (thisCommand, actionCommand) => {
  448. if (thisCommand.opts().trace) {
  449. console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
  450. console.log('arguments: %O', actionCommand.args);
  451. console.log('options: %o', actionCommand.opts());
  452. }
  453. });
  454. ```
  455. The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
  456. The supported events are:
  457. - `preAction`: called before action handler for this command and its subcommands
  458. - `postAction`: called after action handler for this command and its subcommands
  459. The hook is passed the command it was added to, and the command running the action handler.
  460. ## Automated help
  461. The help information is auto-generated based on the information commander already knows about your program. The default
  462. help option is `-h,--help`.
  463. Example file: [pizza](./examples/pizza)
  464. ```bash
  465. $ node ./examples/pizza --help
  466. Usage: pizza [options]
  467. An application for pizza ordering
  468. Options:
  469. -p, --peppers Add peppers
  470. -c, --cheese <type> Add the specified type of cheese (default: "marble")
  471. -C, --no-cheese You do not want any cheese
  472. -h, --help display help for command
  473. ```
  474. A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
  475. further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
  476. ```bash
  477. shell help
  478. shell --help
  479. shell help spawn
  480. shell spawn --help
  481. ```
  482. ### Custom help
  483. You can add extra text to be displayed along with the built-in help.
  484. Example file: [custom-help](./examples/custom-help)
  485. ```js
  486. program
  487. .option('-f, --foo', 'enable some foo');
  488. program.addHelpText('after', `
  489. Example call:
  490. $ custom-help --help`);
  491. ```
  492. Yields the following help output:
  493. ```Text
  494. Usage: custom-help [options]
  495. Options:
  496. -f, --foo enable some foo
  497. -h, --help display help for command
  498. Example call:
  499. $ custom-help --help
  500. ```
  501. The positions in order displayed are:
  502. - `beforeAll`: add to the program for a global banner or header
  503. - `before`: display extra information before built-in help
  504. - `after`: display extra information after built-in help
  505. - `afterAll`: add to the program for a global footer (epilog)
  506. The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
  507. 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:
  508. - error: a boolean for whether the help is being displayed due to a usage error
  509. - command: the Command which is displaying the help
  510. ### Display help after errors
  511. The default behaviour for usage errors is to just display a short error message.
  512. You can change the behaviour to show the full help or a custom help message after an error.
  513. ```js
  514. program.showHelpAfterError();
  515. // or
  516. program.showHelpAfterError('(add --help for additional information)');
  517. ```
  518. ```sh
  519. $ pizza --unknown
  520. error: unknown option '--unknown'
  521. (add --help for additional information)
  522. ```
  523. You can also show suggestions after an error for an unknown command or option.
  524. ```js
  525. program.showSuggestionAfterError();
  526. ```
  527. ```sh
  528. $ pizza --hepl
  529. error: unknown option '--hepl'
  530. (Did you mean --help?)
  531. ```
  532. ### Display help from code
  533. `.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
  534. `.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
  535. `.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
  536. ### .usage and .name
  537. These allow you to customise the usage description in the first line of the help. The name is otherwise
  538. deduced from the (full) program arguments. Given:
  539. ```js
  540. program
  541. .name("my-command")
  542. .usage("[global options] command")
  543. ```
  544. The help will start with:
  545. ```Text
  546. Usage: my-command [global options] command
  547. ```
  548. ### .helpOption(flags, description)
  549. By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.
  550. ```js
  551. program
  552. .helpOption('-e, --HELP', 'read more information');
  553. ```
  554. ### .addHelpCommand()
  555. A 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)`.
  556. You can both turn on and customise the help command by supplying the name and description:
  557. ```js
  558. program.addHelpCommand('assist [command]', 'show assistance');
  559. ```
  560. ### More configuration
  561. The built-in help is formatted using the Help class.
  562. You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.
  563. The data properties are:
  564. - `helpWidth`: specify the wrap width, useful for unit tests
  565. - `sortSubcommands`: sort the subcommands alphabetically
  566. - `sortOptions`: sort the options alphabetically
  567. 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.
  568. Example file: [configure-help.js](./examples/configure-help.js)
  569. ```js
  570. program.configureHelp({
  571. sortSubcommands: true,
  572. subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
  573. });
  574. ```
  575. ## Custom event listeners
  576. You can execute custom actions by listening to command and option events.
  577. ```js
  578. program.on('option:verbose', function () {
  579. process.env.VERBOSE = this.opts().verbose;
  580. });
  581. ```
  582. ## Bits and pieces
  583. ### .parse() and .parseAsync()
  584. The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
  585. If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
  586. - 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
  587. - 'electron': `argv[1]` varies depending on whether the electron application is packaged
  588. - 'user': all of the arguments from the user
  589. For example:
  590. ```js
  591. program.parse(process.argv); // Explicit, node conventions
  592. program.parse(); // Implicit, and auto-detect electron
  593. program.parse(['-f', 'filename'], { from: 'user' });
  594. ```
  595. ### Parsing Configuration
  596. If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
  597. By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
  598. an option for a different purpose in subcommands.
  599. Example file: [positional-options.js](./examples/positional-options.js)
  600. With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
  601. ```sh
  602. program -b subcommand
  603. program subcommand -b
  604. ```
  605. By default options are recognised before and after command-arguments. To only process options that come
  606. before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
  607. without needing to use `--` to end the option processing.
  608. To use pass through options in a subcommand, the program needs to enable positional options.
  609. Example file: [pass-through-options.js](./examples/pass-through-options.js)
  610. 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:
  611. ```sh
  612. program --port=80 arg
  613. program arg --port=80
  614. ```
  615. 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.
  616. By default the argument processing does not display an error for more command-arguments than expected.
  617. To display an error for excess arguments, use`.allowExcessArguments(false)`.
  618. ### Legacy options as properties
  619. Before Commander 7, the option values were stored as properties on the command.
  620. This was convenient to code but the downside was possible clashes with
  621. existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
  622. ```js
  623. program
  624. .storeOptionsAsProperties()
  625. .option('-d, --debug')
  626. .action((commandAndOptions) => {
  627. if (commandAndOptions.debug) {
  628. console.error(`Called ${commandAndOptions.name()}`);
  629. }
  630. });
  631. ```
  632. ### TypeScript
  633. 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.
  634. ```bash
  635. node -r ts-node/register pm.ts
  636. ```
  637. ### createCommand()
  638. This factory function creates a new command. It is exported and may be used instead of using `new`, like:
  639. ```js
  640. const { createCommand } = require('commander');
  641. const program = createCommand();
  642. ```
  643. `createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
  644. when creating subcommands using `.command()`, and you may override it to
  645. customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
  646. ### Node options such as `--harmony`
  647. You can enable `--harmony` option in two ways:
  648. - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
  649. - Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
  650. ### Debugging stand-alone executable subcommands
  651. An executable subcommand is launched as a separate child process.
  652. 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,
  653. the inspector port is incremented by 1 for the spawned subcommand.
  654. If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
  655. ### Override exit and output handling
  656. By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
  657. this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
  658. The 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 help
  659. is not affected by the override which is called after the display.
  660. ```js
  661. program.exitOverride();
  662. try {
  663. program.parse(process.argv);
  664. } catch (err) {
  665. // custom processing...
  666. }
  667. ```
  668. By default Commander is configured for a command-line application and writes to stdout and stderr.
  669. You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
  670. Example file: [configure-output.js](./examples/configure-output.js)
  671. ```js
  672. function errorColor(str) {
  673. // Add ANSI escape codes to display text in red.
  674. return `\x1b[31m${str}\x1b[0m`;
  675. }
  676. program
  677. .configureOutput({
  678. // Visibly override write routines as example!
  679. writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
  680. writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
  681. // Highlight errors in color.
  682. outputError: (str, write) => write(errorColor(str))
  683. });
  684. ```
  685. ### Additional documentation
  686. There is more information available about:
  687. - [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
  688. - [options taking varying arguments](./docs/options-taking-varying-arguments.md)
  689. ## Examples
  690. In a single command program, you might not need an action handler.
  691. Example file: [pizza](./examples/pizza)
  692. ```js
  693. const { program } = require('commander');
  694. program
  695. .description('An application for pizza ordering')
  696. .option('-p, --peppers', 'Add peppers')
  697. .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')
  698. .option('-C, --no-cheese', 'You do not want any cheese');
  699. program.parse();
  700. const options = program.opts();
  701. console.log('you ordered a pizza with:');
  702. if (options.peppers) console.log(' - peppers');
  703. const cheese = !options.cheese ? 'no' : options.cheese;
  704. console.log(' - %s cheese', cheese);
  705. ```
  706. In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).
  707. Example file: [deploy](./examples/deploy)
  708. ```js
  709. const { Command } = require('commander');
  710. const program = new Command();
  711. program
  712. .version('0.0.1')
  713. .option('-c, --config <path>', 'set config path', './deploy.conf');
  714. program
  715. .command('setup [env]')
  716. .description('run setup commands for all envs')
  717. .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')
  718. .action((env, options) => {
  719. env = env || 'all';
  720. console.log('read config from %s', program.opts().config);
  721. console.log('setup for %s env(s) with %s mode', env, options.setup_mode);
  722. });
  723. program
  724. .command('exec <script>')
  725. .alias('ex')
  726. .description('execute the given remote cmd')
  727. .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')
  728. .action((script, options) => {
  729. console.log('read config from %s', program.opts().config);
  730. console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);
  731. }).addHelpText('after', `
  732. Examples:
  733. $ deploy exec sequential
  734. $ deploy exec async`
  735. );
  736. program.parse(process.argv);
  737. ```
  738. More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
  739. ## Support
  740. The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v12.
  741. (For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.)
  742. The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
  743. ### Commander for enterprise
  744. Available as part of the Tidelift Subscription
  745. 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)