tis-cli前端项目快速搭建命令行工具
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.

1021 lines
36 KiB

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