source: frontend/node_modules/commander/Readme.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

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