UNPKG

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