source: trip-planner-front/node_modules/commander/Readme.md@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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