Skip to content
Myr

docs(README): Tweak formatting, punctuation for clarity (#2465)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* docs(README): Tweak formatting, punctuation for clarity * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * docs(README): Rewrites requested by @shadowspawn * docs(README): One more rewrite, @shadowspawn ;-) * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> * Update Readme.md Co-authored-by: John Gee <john@ruru.gen.nz> ---------

authored by Zearin · committed by GitHub · parent 4208a96 · Browse files · 1 file+78 added−64 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: John Gee <john@ruru.gen.nz>

Diff stats

1 file+78 added−64 removed

  • other:+78 added−64 removed

1 file+78 added−64 removed

modified:Readme.md+78 added-64 removed
152 unmodified lines
153// CommonJS (.cjs)154const { program } = require('commander');155```156157For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.157For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.158159```js160// CommonJS (.cjs)161const { Command } = require('commander');
13 unmodified lines
175```176177## Options178179Options 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 ('|'). To allow a wider range of short-ish flags than just180single characters, you may also have two long options. Examples:179Options 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, a space, or a vertical bar (`|`). To allow a wider range of short-ish flags than just single characters, you may also have two long options.180181```js182program183 .option('-p, --port <number>', 'server port number')
2 unmodified lines
186```187188The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.189191Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.190Multi-word options like `--template-engine` are normalized to camelCase option names, resulting in properties such as `program.opts().templateEngine`.191193An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option.192An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly, or follow an `=` for a long option.193194```sh195serve -p 80196serve -p80
46 unmodified lines
243- cheese244```245246Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.248For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.247For example, `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.248249Options with an expected option-argument are greedy and will consume the following argument whatever the value.250So `--id -xyz` reads `-xyz` as the option-argument.251
22 unmodified lines
274```275276### Other option types, negatable boolean and boolean|value277279You can define a boolean option long name with a leading `no-` to set the option value to false when used.280Defined alone this also makes the option true by default.278You can define a boolean option long name with a leading `no-` to set the option value to `false` when used.279Defined alone, this also makes the option `true` by default.280281If you define `--foo` first, adding `--no-foo` does not change the default value from what it would282otherwise be.283
23 unmodified lines
307You ordered a pizza with no sauce and no cheese308```309310You can specify an option which may be used as a boolean option but may optionally take an option-argument312(declared with square brackets like `--optional [value]`).311(declared with square brackets, like `--optional [value]`).312313Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)314315```js
24 unmodified lines
340For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).341342### Required option343345You 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.344You 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 (e.g., from environment). 345346The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.347348Example file: [options-required.js](./examples/options-required.js)349350```js351program
11 unmodified lines
363364You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you365can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments366are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value366is specified in the same argument as the option then no further values are read.367is specified in the same argument as the option, then no further values are read.368369Example file: [options-variadic.js](./examples/options-variadic.js)370371```js
22 unmodified lines
394For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).395396### Version option397397The 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.398The optional `.version()` method adds handling for displaying the command version. The default option flags are `-V` and `--version`. When used, the command prints the version number and exits.399400```js401program.version('0.0.1');402```
2 unmodified lines
405$ ./examples/pizza -V4060.0.1407```408408You may change the flags and description by passing additional parameters to the `version` method, using409the same syntax for flags as the `option` method.409You may change the flags and description by passing additional parameters to the `.version()` method, using410the same syntax for flags as the `.option()` method.411412```js413program.version('0.0.1', '-v, --vers', 'output the current version');414```
38 unmodified lines
453$ extra --disable-server --port 8000454error: option '--disable-server' cannot be used with option '-p, --port <number>'455```456456Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option).457Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [`.requiredOption()`](#required-option).458459### Custom option processing460461You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
59 unmodified lines
521```522523## Commands524524You 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)).525You 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. (More detail about this later.)526527Subcommands may be nested. Example file: [nestedCommands.js](./examples/nestedCommands.js).528529In 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...`.530531You can use `.addCommand()` to add an already configured subcommand to the program.532
22 unmodified lines
555```556557Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will558remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other556subcommand is specified ([example](./examples/defaultCommand.js)).559subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)560558You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js))561You can add alternative names for a command with `.alias()`. (Example file: [alias.js](./examples/alias.js).)562560`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation, any later setting changes to the parent are not inherited.563`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.564565For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.566567### Command-arguments568569For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This567is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands568you can instead use the following method.570is the only method usable for subcommands implemented using a stand-alone executable.571570To configure a command, you can use `.argument()` to specify each expected command-argument.572Alternatively, you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument.573You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.574You can specify a default value for an optional command-argument.575576Example file: [argument.js](./examples/argument.js)
8 unmodified lines
585 console.log('password:', password);586 });587```588587 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you588 append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:589The last argument of a command can be variadic, and _only_ the last argument. To make an argument variadic, simply590append `...` to the argument name.591592A variadic argument is passed to the action handler as an array.593594```js595program596 .version('0.1.0')597 .command('rmdir')
67 unmodified lines
665 console.log(`Thank-you ${title}${name}`);666 });667```668665If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).669If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. If you use a function expression (but not an arrow function), the `this` keyword is set to the running command.670671Example file: [action-this.js](./examples/action-this.js)672673```js
5 unmodified lines
679 console.error('Run script %s on port %s', this.args[0], this.opts().port);680 });681```682679You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.683You may supply an `async` action handler, in which case you call `.parseAsync()` rather than `.parse()`.684685```js686async function run() { /* code goes here */ }687
4 unmodified lines
692 await program.parseAsync(process.argv);693}694```695692A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments or excess arguments will be reported as an error. You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.696A command's options and arguments on the command line are validated when the command is used. Any unknown options, missing arguments, or excess arguments will be reported as an error. 697698You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.699700### Stand-alone executable (sub)commands701702When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.697Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand`, like `pm-install` or `pm-search` in the example below. The search includes trying common file extensions, like `.js`.703Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand` (like `pm-install` or `pm-search` in the example below). The search includes trying common file extensions, like `.js`.704You may specify a custom name (and path) with the `executableFile` configuration option.705You may specify a custom search directory for subcommands with `.executableDir()`.706707You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
31 unmodified lines
739 }740 });741```742737The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.743The callback hook can be `async`, in which case you call `.parseAsync()` rather than `.parse()`. You can add multiple hooks per event.744745The supported events are:746747| event name | when hook called | callback parameters |748| :-- | :-- | :-- |749| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |750| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |751746For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).752For an overview of the life cycle events, see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).753754## Automated help755756The help information is auto-generated based on the information commander already knows about your program. The default
66 unmodified lines
823The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.824825The 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:826821- error: a boolean for whether the help is being displayed due to a usage error822- command: the Command which is displaying the help827- `error`: a boolean for whether the help is being displayed due to a usage error828- `command`: the `Command` which is displaying the help829830### Display help after errors831832The default behaviour for usage errors is to just display a short error message.
35 unmodified lines
868### .name869870The command name appears in the help, and is also used for locating stand-alone executable subcommands.871866You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will872You may specify the program name using `.name()` or in the `Command` constructor. For the program, Commander will873fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies874depending on how your program is launched, so you may wish to specify it explicitly.875876```js
1 unmodified line
878const pm = new Command('pm');879```880881Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,876then set the name using `.name()` or in the Command constructor.882then set the name using `.name()` or in the `Command` constructor.883884### .usage885886This allows you to customise the usage description in the first line of the help. Given:
25 unmodified lines
912```913914### .helpOption(flags, description)915910By default, every command has a help option. You may change the default help flags and description. Pass false to disable the built-in help option.916By default, every command has a help option. You may change the default help flags and description. Pass `false` to disable the built-in help option.917918```js919program920 .helpOption('-e, --HELP', 'read more information');921```922917(Or use `.addHelpOption()` to add an option you construct yourself.)923Alternatively, use `.addHelpOption()` to add an option you construct yourself.924925### .helpCommand()926921A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.helpCommand(true)` and `.helpCommand(false)`.927A help command is added by default if your command has subcommands. You can explicitly turn the implicit help command on or off with `.helpCommand(true)` and `.helpCommand(false)`.928929You can both turn on and customise the help command by supplying the name and description:930931```js932program.helpCommand('assist [command]', 'show assistance');933```934929(Or use `.addHelpCommand()` to add a command you construct yourself.)935Alternatively, use `.addHelpCommand()` to add a command you construct yourself.936937### Help Groups938939The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups934with different headings. The high-level way is to set the desired group heading while adding the options and commands,935using `.optionsGroup()` and `.commandsGroup()`. The low-level way is using `.helpGroup()` on an individual `Option` or `Command`940with different headings. 941942- The high-level way is to set the desired group heading while adding the options and commands, using `.optionsGroup()` and `.commandsGroup()`. 943- The low-level way is using `.helpGroup()` on an individual `Option` or `Command`.944945Example file: [help-groups.js](./examples/help-groups.js)946947### More configuration948941The built-in help is formatted using the Help class.942You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing Help using `.createHelp()` .949The built-in help is formatted using the `Help` class.950You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing `Help` using `.createHelp()` .951944Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `styleTitle()`.952Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `.styleTitle()`.953946For more detail and examples of changing the displayed text, color, and layout see [help in depth](./docs/help-in-depth.md).954For more detail and examples of changing the displayed text, color, and layout, see: [help in depth](./docs/help-in-depth.md).955956## Custom event listeners957950You can execute custom actions by listening to command and option events.958You can execute custom actions by listening to `command` and `option` events.959960```js961program.on('option:verbose', function () {962 process.env.VERBOSE = this.opts().verbose;
5 unmodified lines
968### .parse() and .parseAsync()969970Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!971964Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:972Or, call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:973974- `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that975- `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged976- `'user'`: just user arguments
5 unmodified lines
982program.parse(process.argv); // assume argv[0] is app and argv[1] is script983program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]984```985978Use parseAsync instead of parse if any of your action handlers are async.986Use `.parseAsync()` instead of `.parse()` if any of your action handlers are async.987988### Parsing Configuration989990If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
26 unmodified lines
10171018By 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.10191020By default, the argument processing displays an error for more command-arguments than expected.1013To suppress the error for excess arguments, use`.allowExcessArguments()`.1021To suppress the error for excess arguments, use `.allowExcessArguments()`.10221023### Legacy options as properties10241025Before Commander 7, the option values were stored as properties on the command.1026This was convenient to code, but the downside was possible clashes with1019existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.1027existing properties of `Command`. 10281029You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.10301031```js1032program1033 .storeOptionsAsProperties()1034 .option('-d, --debug')
5 unmodified lines
1040```10411042### TypeScript10431034extra-typings: There is an optional project to infer extra type information from the option and argument definitions.1044**extra-typings:** There is an optional project to infer extra type information from the option and argument definitions.1045This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.1036See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more.1046For more, see the repo: [commander-js/extra-typings](https://github.com/commander-js/extra-typings).10471038```1048```ts1049import { Command } from '@commander-js/extra-typings';1050```10511042ts-node: If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.1052**ts-node:** If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly, e.g.:10531054```sh1055node -r ts-node/register pm.ts1056```
6 unmodified lines
1063const { createCommand } = require('commander');1064const program = createCommand();1065```10661057`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally1067`createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally1068when creating subcommands using `.command()`, and you may override it to1059customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).1069customise the new subcommand. Example file: [custom-command-class.js](./examples/custom-command-class.js).10701071### Node options such as `--harmony`10721073You can enable `--harmony` option in two ways:10741065- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)1075- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note: Windows does not support this pattern.)1076- Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.10771078### Debugging stand-alone executable subcommands1079
1 unmodified line
10811082If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,1083the inspector port is incremented by 1 for the spawned subcommand.10841075If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.1085If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your `launch.json` configuration.10861087### npm run-script10881079By default, when you call your program using run-script, `npm` will parse any options on the command-line and they will not reach your program. Use1089By default, when you call your program using `run-script`, `npm` will parse any options on the command-line and they will not reach your program. Use1090 `--` to stop the npm option parsing and pass through all the arguments.10911082 The synopsis for [npm run-script](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:1092 The synopsis for [`npm run-script`](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:10931094```console1095npm run-script <command> [-- <args>]1096```
1 unmodified line
1098### Display error10991100This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)11011092As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)1102As well as the error message, you can optionally specify the `exitCode` (used with `process.exit()`)1103and `code` (used with `CommanderError`).11041105```js1106program.error('Password must be longer than four characters');
1 unmodified line
1108```11091110### Override exit and output handling11111102By default, Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override1112By default, Commander calls `process.exit()` when it detects errors, or after displaying the help or version. You can override1113this behaviour and optionally supply a callback. The default override throws a `CommanderError`.11141105The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`.1106Commander expects the callback to terminate the normal program flow, and will call `process.exit` if the callback returns.1107The normal display of error messages or version or help is not affected by the override which is called after the display.1115The override callback is passed a `CommanderError` with the properties:1116- `exitCode`: number1117- `code`: string 1118- `message`: string11191120Commander expects the callback to terminate the normal program flow, and will call `process.exit()` if the callback returns.1121The normal display of error messages or version or help is not affected by the override, which is called after the display.11221123```js1124program.exitOverride();11251126try {
47 unmodified lines