node.js command-line interfaces made easy

Overview

Commander.js

Build Status NPM Version NPM Downloads Install Size

The complete solution for node.js command-line interfaces.

Read this in other languages: English | 简体中文

For information about terms used in this document see: terminology

Installation

npm install commander

Declaring program variable

Commander exports a global object which is convenient for quick programs. This is used in the examples in this README for brevity.

const { program } = require('commander');
program.version('0.0.1');

For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.

const { Command } = require('commander');
const program = new Command();
program.version('0.0.1');

For named imports in ECMAScript modules, import from commander/esm.mjs.

// index.mjs
import { Command } from 'commander/esm.mjs';
const program = new Command();

And in TypeScript:

// index.ts
import { Command } from 'commander';
const program = new Command();

Options

Options are defined with the .option() method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').

The 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.

Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value). For example -a -b -p 80 may be written as -ab -p80 or even -abp80.

You can use -- to indicate the end of the options, and any remaining arguments will be used without being interpreted.

By default options on the command line are not positional, and can be specified before or after other arguments.

Common option types, boolean and value

The two most used option types are a boolean option, and an option which takes its value from the following argument (declared with angle brackets like --expect <value>). Both are undefined unless specified on command line.

Example file: options-common.js

program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
$ pizza-options -d
{ debug: true, small: undefined, pizzaType: undefined }
pizza details:
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -ds -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese

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.

Default option value

You can specify a default value for an option which takes a value.

Example file: options-defaults.js

program
  .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');

program.parse();

console.log(`cheese: ${program.opts().cheese}`);
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton

Other option types, negatable boolean and boolean|value

You can define a boolean option long name with a leading no- to set the option value to false when used. Defined alone this also makes the option true by default.

If you define --foo first, adding --no-foo does not change the default value from what it would otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line.

Example file: options-negatable.js

program
  .option('--no-sauce', 'Remove sauce')
  .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  .option('--no-cheese', 'plain with no cheese')
  .parse();

const options = program.opts();
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese

You can specify an option which may be used as a boolean option but may optionally take an option-argument (declared with square brackets like --optional [value]).

Example file: options-boolean-or-value.js

program
  .option('-c, --cheese [type]', 'Add cheese with optional type');

program.parse(process.argv);

const options = program.opts();
if (options.cheese === undefined) console.log('no cheese');
else if (options.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${options.cheese}`);
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella

For information about possible ambiguous cases, see options taking varying arguments.

Required option

You may specify a required (mandatory) option using .requiredOption. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as .option in format, taking flags and description, and optional default value or custom processing.

Example file: options-required.js

program
  .requiredOption('-c, --cheese <type>', 'pizza must have cheese');

program.parse();
$ pizza
error: required option '-c, --cheese <type>' not specified

Variadic option

You may make an option variadic by appending ... to the value placeholder when declaring the option. On the command line you can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments are read until the first argument starting with a dash. The special argument -- stops option processing entirely. If a value is specified in the same argument as the option then no further values are read.

Example file: options-variadic.js

program
  .option('-n, --number <numbers...>', 'specify numbers')
  .option('-l, --letter [letters...]', 'specify letters');

program.parse();

console.log('Options: ', program.opts());
console.log('Remaining arguments: ', program.args);
$ collect -n 1 2 3 --letter a b c
Options:  { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
Remaining arguments:  []
$ collect --letter=A -n80 operand
Options:  { number: [ '80' ], letter: [ 'A' ] }
Remaining arguments:  [ 'operand' ]
$ collect --letter -n 1 -n 2 3 -- operand
Options:  { number: [ '1', '2', '3' ], letter: true }
Remaining arguments:  [ 'operand' ]

For information about possible ambiguous cases, see options taking varying arguments.

Version option

The optional version method adds handling for displaying the command version. The default option flags are -V and --version, and when present the command prints the version number and exits.

program.version('0.0.1');
$ ./examples/pizza -V
0.0.1

You may change the flags and description by passing additional parameters to the version method, using the same syntax for flags as the option method.

program.version('0.0.1', '-v, --vers', 'output the current version');

More configuration

You can add most options using the .option() method, but there are some additional features available by constructing an Option explicitly for less common cases.

Example file: options-extra.js

program
  .addOption(new Option('-s, --secret').hideHelp())
  .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
  .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']));
$ extra --help
Usage: help [options]

Options:
  -t, --timeout <delay>  timeout in seconds (default: one minute)
  -d, --drink <size>     drink cup size (choices: "small", "medium", "large")
  -h, --help             display help for command

$ extra --drink huge
error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.

Custom option processing

You may specify a function to do custom processing of option-arguments. The callback function receives two parameters, the user specified option-argument and the previous value for the option. It returns the new value for the option.

This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.

You can optionally specify the default/starting value for the option after the function parameter.

Example file: options-custom-processing.js

function myParseInt(value, dummyPrevious) {
  // parseInt takes a string and a radix
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidOptionArgumentError('Not a number.');
  }
  return parsedValue;
}

function increaseVerbosity(dummyValue, previous) {
  return previous + 1;
}

function collect(value, previous) {
  return previous.concat([value]);
}

function commaSeparatedList(value, dummyPrevious) {
  return value.split(',');
}

program
  .option('-f, --float <number>', 'float argument', parseFloat)
  .option('-i, --integer <number>', 'integer argument', myParseInt)
  .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  .option('-c, --collect <value>', 'repeatable value', collect, [])
  .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;

program.parse();

const options = program.opts();
if (options.float !== undefined) console.log(`float: ${options.float}`);
if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
if (options.collect.length > 0) console.log(options.collect);
if (options.list !== undefined) console.log(options.list);
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]

Commands

You can specify (sub)commands using .command() or .addCommand(). There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested (example).

In 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....

You can use .addCommand() to add an already configured subcommand to the program.

For example:

// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
  .action((source, destination) => {
    console.log('clone command called');
  });

// Command implemented using stand-alone executable file (description is second parameter to `.command`)
// Returns `this` for adding more commands.
program
  .command('start <service>', 'start named service')
  .command('stop [service]', 'stop named service, or all if no name supplied');

// Command prepared separately.
// Returns `this` for adding more commands.
program
  .addCommand(build.makeBuildCommand());

Configuration options can be passed with the call to .command() and .addCommand(). Specifying hidden: true will remove the command from the generated help output. Specifying isDefault: true will run the subcommand if no other subcommand is specified (example).

Specify the argument syntax

You use .arguments to specify the expected command-arguments for the top-level command, and for subcommands they are usually included in the .command call. Angled brackets (e.g. <required>) indicate required command-arguments. Square brackets (e.g. [optional]) indicate optional command-arguments. You can optionally describe the arguments in the help by supplying a hash as second parameter to .description().

Example file: arguments.js

program
  .version('0.1.0')
  .arguments('<username> [password]')
  .description('test command', {
    username: 'user to login',
    password: 'password for user, if required'
  })
  .action((username, password) => {
    console.log('username:', username);
    console.log('environment:', password || 'no password given');
  });

The last argument of a command can be variadic, and only the last argument. To make an argument variadic you append ... to the argument name. For example:

program
  .version('0.1.0')
  .command('rmdir <dirs...>')
  .action(function (dirs) {
    dirs.forEach((dir) => {
      console.log('rmdir %s', dir);
    });
  });

The variadic argument is passed to the action handler as an array.

Action handler

The action handler gets passed a parameter for each command-argument you declared, and two additional parameters which are the parsed options and the command object itself.

Example file: thank.js

program
  .arguments('<name>')
  .option('-t, --title <honorific>', 'title to use before name')
  .option('-d, --debug', 'display some debugging')
  .action((name, options, command) => {
    if (options.debug) {
      console.error('Called %s with options %o', command.name(), options);
    }
    const title = options.title ? `${options.title} ` : '';
    console.log(`Thank-you ${title}${name}`);
  });

You may supply an async action handler, in which case you call .parseAsync rather than .parse.

async function run() { /* code goes here */ }

async function main() {
  program
    .command('run')
    .action(run);
  await program.parseAsync(process.argv);
}

A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with .allowUnknownOption(). By default it is not an error to pass more arguments than declared, but you can make this an error with .allowExcessArguments(false).

Stand-alone executable (sub)commands

When .command() is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands. Commander will search the executables in the directory of the entry script (like ./examples/pm) with the name program-subcommand, like pm-install, pm-search. You can specify a custom name with the executableFile configuration option.

You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.

Example file: pm

program
  .version('0.1.0')
  .command('install [name]', 'install one or more packages')
  .command('search [query]', 'search with optional query')
  .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
  .command('list', 'list packages installed', { isDefault: true });

program.parse(process.argv);

If the program is designed to be installed globally, make sure the executables have proper modes, like 755.

Automated help

The help information is auto-generated based on the information commander already knows about your program. The default help option is -h,--help.

Example file: pizza

$ node ./examples/pizza --help
Usage: pizza [options]

An application for pizza ordering

Options:
  -p, --peppers        Add peppers
  -c, --cheese <type>  Add the specified type of cheese (default: "marble")
  -C, --no-cheese      You do not want any cheese
  -h, --help           display help for command

A help command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show further help for the subcommand. These are effectively the same if the shell program has implicit help:

shell help
shell --help

shell help spawn
shell spawn --help

Custom help

You can add extra text to be displayed along with the built-in help.

Example file: custom-help

program
  .option('-f, --foo', 'enable some foo');

program.addHelpText('after', `

Example call:
  $ custom-help --help`);

Yields the following help output:

Usage: custom-help [options]

Options:
  -f, --foo   enable some foo
  -h, --help  display help for command

Example call:
  $ custom-help --help

The positions in order displayed are:

  • beforeAll: add to the program for a global banner or header
  • before: display extra information before built-in help
  • after: display extra information after built-in help
  • afterAll: add to the program for a global footer (epilog)

The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.

The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:

  • error: a boolean for whether the help is being displayed due to a usage error
  • command: the Command which is displaying the help

Display help from code

.help(): display help information and exit immediately. You can optionally pass { error: true } to display on stderr and exit with an error status.

.outputHelp(): output help information without exiting. You can optionally pass { error: true } to display on stderr.

.helpInformation(): get the built-in command help information as a string for processing or displaying yourself.

.usage and .name

These allow you to customise the usage description in the first line of the help. The name is otherwise deduced from the (full) program arguments. Given:

program
  .name("my-command")
  .usage("[global options] command")

The help will start with:

Usage: my-command [global options] command

.helpOption(flags, description)

By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.

program
  .helpOption('-e, --HELP', 'read more information');

.addHelpCommand()

A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with .addHelpCommand() and .addHelpCommand(false).

You can both turn on and customise the help command by supplying the name and description:

program.addHelpCommand('assist [command]', 'show assistance');

More configuration

The built-in help is formatted using the Help class. You can configure the Help behaviour by modifying data properties and methods using .configureHelp(), or by subclassing using .createHelp() if you prefer.

The data properties are:

  • helpWidth: specify the wrap width, useful for unit tests
  • sortSubcommands: sort the subcommands alphabetically
  • sortOptions: sort the options alphabetically

There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a term and description. Take a look at .formatHelp() to see how they are used.

Example file: configure-help.js

program.configureHelp({
  sortSubcommands: true,
  subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
});

Custom event listeners

You can execute custom actions by listening to command and option events.

program.on('option:verbose', function () {
  process.env.VERBOSE = this.opts().verbose;
});

program.on('command:*', function (operands) {
  console.error(`error: unknown command '${operands[0]}'`);
  const availableCommands = program.commands.map(cmd => cmd.name());
  mySuggestBestMatch(operands[0], availableCommands);
  process.exitCode = 1;
});

Bits and pieces

.parse() and .parseAsync()

The first argument to .parse is the array of strings to parse. You may omit the parameter to implicitly use process.argv.

If the arguments follow different conventions than node you can pass a from option in the second parameter:

  • 'node': default, argv[0] is the application and argv[1] is the script being run, with user parameters after that
  • 'electron': argv[1] varies depending on whether the electron application is packaged
  • 'user': all of the arguments from the user

For example:

program.parse(process.argv); // Explicit, node conventions
program.parse(); // Implicit, and auto-detect electron
program.parse(['-f', 'filename'], { from: 'user' });

Parsing Configuration

If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.

By default program options are recognised before and after subcommands. To only look for program options before subcommands, use .enablePositionalOptions(). This lets you use an option for a different purpose in subcommands.

Example file: positional-options.js

With positional options, the -b is a program option in the first line and a subcommand option in the second line:

program -b subcommand
program subcommand -b

By default options are recognised before and after command-arguments. To only process options that come before the command-arguments, use .passThroughOptions(). This lets you pass the arguments and following options through to another program without needing to use -- to end the option processing. To use pass through options in a subcommand, the program needs to enable positional options.

Example file: pass-through-options.js

With pass through options, the --port=80 is a program option in the first line and passed through as a command-argument in the second line:

program --port=80 arg
program arg --port=80

By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use .allowUnknownOption(). This lets you mix known and unknown options.

By default the argument processing does not display an error for more command-arguments than expected. To display an error for excess arguments, use.allowExcessArguments(false).

Legacy options as properties

Before Commander 7, the option values were stored as properties on the command. This was convenient to code but the downside was possible clashes with existing properties of Command. You can revert to the old behaviour to run unmodified legacy code by using .storeOptionsAsProperties().

program
  .storeOptionsAsProperties()
  .option('-d, --debug')
  .action((commandAndOptions) => {
    if (commandAndOptions.debug) {
      console.error(`Called ${commandAndOptions.name()}`);
    }
  });

TypeScript

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.

node -r ts-node/register pm.ts

createCommand()

This factory function creates a new command. It is exported and may be used instead of using new, like:

const { createCommand } = require('commander');
const program = createCommand();

createCommand is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally when creating subcommands using .command(), and you may override it to customise the new subcommand (example file custom-command-class.js).

Node options such as --harmony

You can enable --harmony option in two ways:

  • Use #! /usr/bin/env node --harmony in the subcommands scripts. (Note Windows does not support this pattern.)
  • Use the --harmony option when call the command, like node --harmony examples/pm publish. The --harmony option will be preserved when spawning subcommand process.

Debugging stand-alone executable subcommands

An executable subcommand is launched as a separate child process.

If you are using the node inspector for debugging executable subcommands using node --inspect et al, the inspector port is incremented by 1 for the spawned subcommand.

If you are using VSCode to debug executable subcommands you need to set the "autoAttachChildProcesses": true flag in your launch.json configuration.

Override exit and output handling

By default Commander calls process.exit when it detects errors, or after displaying the help or version. You can override this behaviour and optionally supply a callback. The default override throws a CommanderError.

The override callback is passed a CommanderError with properties exitCode number, code string, and message. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help is not affected by the override which is called after the display.

program.exitOverride();

try {
  program.parse(process.argv);
} catch (err) {
  // custom processing...
}

By default Commander is configured for a command-line application and writes to stdout and stderr. You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.

Example file: configure-output.js

function errorColor(str) {
  // Add ANSI escape codes to display text in red.
  return `\x1b[31m${str}\x1b[0m`;
}

program
  .configureOutput({
    // Visibly override write routines as example!
    writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
    writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
    // Highlight errors in color.
    outputError: (str, write) => write(errorColor(str))
  });

Additional documentation

There is more information available about:

Examples

In a single command program, you might not need an action handler.

Example file: pizza

const { program } = require('commander');

program
  .description('An application for pizza ordering')
  .option('-p, --peppers', 'Add peppers')
  .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')
  .option('-C, --no-cheese', 'You do not want any cheese');

program.parse();

const options = program.opts();
console.log('you ordered a pizza with:');
if (options.peppers) console.log('  - peppers');
const cheese = !options.cheese ? 'no' : options.cheese;
console.log('  - %s cheese', cheese);

In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).

Example file: deploy

const { Command } = require('commander');
const program = new Command();

program
  .version('0.0.1')
  .option('-c, --config <path>', 'set config path', './deploy.conf');

program
  .command('setup [env]')
  .description('run setup commands for all envs')
  .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')
  .action((env, options) => {
    env = env || 'all';
    console.log('read config from %s', program.opts().config);
    console.log('setup for %s env(s) with %s mode', env, options.setup_mode);
  });

program
  .command('exec <script>')
  .alias('ex')
  .description('execute the given remote cmd')
  .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')
  .action((script, options) => {
    console.log('read config from %s', program.opts().config);
    console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);
  }).addHelpText('after', `
Examples:
  $ deploy exec sequential
  $ deploy exec async`
  );
  
program.parse(process.argv);

More samples can be found in the examples directory.

Support

The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v10. (For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.)

The main forum for free and community support is the project Issues on GitHub.

Commander for enterprise

Available as part of the Tidelift Subscription

The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • feat(option): allow to set options as conflicting

    feat(option): allow to set options as conflicting

    Pull Request

    Hello 👋 Thank you for this lovely package, this PR implements exclusive options (see details below). ~~Happy to rename it to conflicts~~ (edit: done) or anything else you find suiting, and of course open to any kind of feedback (especially if you think this should be user code and not package code). I searched previous issues and PRs and could only find this related comment: https://github.com/tj/commander.js/issues/1358#issuecomment-695149256

    Problem

    I would like to configure options that are mutually exclusive. For example --json (to set the output type), conflicts with --silent (to suppress output).

    Related to https://github.com/tj/commander.js/issues/1358#issuecomment-695149256

    Solution

    Added a new option method conflicts that accepts an array of strings (or a single string) with options that conflict with the configured option.

    • [x] TypeScript typings
    • [x] JSDoc documentation in code
    • [x] tests
    • [x] README
    • [x] examples/

    ChangeLog

    feat(option): allow to configure conflicting options

    enhancement 
    opened by erezrokah 58
  • Required arguments for options and commands are not enforced

    Required arguments for options and commands are not enforced

    It would be pretty awesome to have support for required arguments. Although there is support for required argument values, there doesn't appear to be anything for ensuring the argument has been specified.

    For example;

        -e, --entry <name>          Add module to entry point
    

    I'd like to make it so an error is raised if -e has not been specified like so;

      error: option `-e, --entry <name>' missing
    
    enhancement 
    opened by foxx 41
  • Add support for config files

    Add support for config files

    Problem

    Adding support of config files when you have an option with a default value and you want the following priorities, is complicated.

    1. Value from the command line
    2. Otherwise value from the config file
    3. Otherwise the default value

    Because commander has no built-in support for config files, you can't use all its power, because options object that you get by calling opts() contains mixed default parameters (point 1 from above) and cli parameters (3) and you should manually inspect each option with default to correctly apply the config file (2) parameters. I would like if commander could do this for me.

    The current workaround looks like this:

    import { Command, Option } from "commander";
    
    /// All options with defaults should be declared there
    const DEFAULTS = {
      optionWithDefault: "default value",
    };
    let options = new Command()
      .option("--config <json>")
      .addOption(
        new Option("--option-with-default <value>")
          .default(DEFAULTS.optionWithDefault)
      )
      .parse()
      .opts();
    
    // Remove all default options from the parsed options
    for (const key of Object.keys(DEFAULTS)) {
      if (DEFAULTS[key] === options[key]) {
        delete options[key];
      }
    }
    
    const cliOptions = options;
    const config = options.config;
    delete options.config;
    
    options = Object.assign({}, DEFAULTS);
    if (config) {
      options = Object.assign(options, readFileAsJSON(config));
    }
    

    but it is incomplete: if I specify --option-with-default "default value" in the command line the code above will think that it is default value and override it with the config option value, which is not expected. To solve this problem I'll have to parse options manually, which effectively makes commander useless in such scenario.

    Proposal

    The proposed API could looks like:

    import path from "path";
    
    let options = new Command()
      .option("--option <value>")
      .addOption(
        new Option("--default <value>")
          .default("default")
      )
      .addOption(
        new Option("--config <file>")
          // Optional function should return Object with properties with values
          // from the config file
          // By default uses the specified function that could process both .json
          // and .js (as CommonJS modules, like eslint) config files
          .config(val => require(path.resolve(val)))
          // If config not specified and have a default, this file tried to read
          // using config read function from `.config()`
          .default(".config.js")
      )
    

    The examples for the CLI definition below:

    .config.js does not exist

    • Command: prog Result:
      { default: "default" }
      
    • Command: prog --default a Result:
      { default: "a" }
      
    • Command: prog --option b Result:
      { default: "default", option: "b" }
      

    .config.js contains option

    module.exports = {
      option: "config",
    };
    
    • Command: prog Result:
      { default: "default", option: "config" }
      
    • Command: prog --default a Result:
      { default: "a", option: "config" }
      
    • Command: prog --option b Result:
      { default: "default", option: "b" }
      

    .config.js contains default

    module.exports = {
      default: "config",
    };
    
    • Command: prog Result:
      { default: "config" }
      
    • Command: prog --default a Result:
      { default: "a" }
      
    • Command: prog --option b Result:
      { default: "config", option: "b" }
      
    enhancement 
    opened by Mingun 35
  • Subcommands syntax and usage

    Subcommands syntax and usage

    Hi there !

    Is it possible to define subcommands in commander ?

    e.g.

    node script.js thecommand subcommand1 -op1 -op2
    node script.js thecommand subcommand2 -op3
    

    A particularly intended usage would be to define program.command('thecommand').action('./path/to/subcommands.js') in root index.js or other starting point and then I would have some dir with commands (path/to/subcommands), where I can then define subcommands

    program
      .command('subcommand1').action(...)
      .command('subcommand2').action(...)
    

    or maybe some kind of array with commands

    module.exports = [
      { command: 'subcommand1', options: '...', action: someFn },
      { command: 'subcommand2', options: '...', action: someFn }
    ]
    

    I found something promising here, but it is not documented and I cannot figure out how it works

    opened by a-fas 29
  • Run default command if it's not just *

    Run default command if it's not just *

    Pull Request

    Problem

    I'm trying to build a command like the one below

    cli [optional]
    cli subcommand [optional]
    

    The implementation loosely looks something like this...

    program
    	.argument('[optional]')
    	.option('-d', 'do a thing')
    	.action(() => { console.log('whoop') })
    
    program
    	.command('subcommand [optional]')
    	.option('-b', 'blah')
    	.action(() => { console.log('beh') }
    
    program.parse(process.argv)
    

    When trying to run cli -d the action for the main command won't run. Using program subcommand -b runs fine.

    Solution

    I traced it down to https://github.com/tj/commander.js/pull/844 which contains a fix for this issue: https://github.com/tj/commander.js/issues/843. In said issue, @Skywalker13 reported that it was expected that a program that only had one command registered that was the * command shouldn't trigger an action. The fix in #844 just changed it so that if there were any commands registered then the default command won't run.

    I preserved the behavior from #843 while also ensuring that valid usecases (i.e. when commands are present besides *) will still cause the base action to trigger.

    ChangeLog

    Run actions when no optional arguments are provided and real commands are registered.

    semver: major 
    opened by zephraph 26
  • fix wrapped & indented option, command and argument descriptions

    fix wrapped & indented option, command and argument descriptions

    Long Command, Option and Argument descriptions are not wrapped to the available TTY columns which make it hard to read the descriptions if they contain a lot of information. This change wraps the descriptions to the available space and also indents them so that they align correctly.

    Issues:

    • #579
    • #759
    • #396

    Example Output:

    Usage: mite-project-update [options] [projectId]
    
    Updates a specific project
    
    Arguments:
    
      projectId                    Id of the project of which the note should be altered Cupidatat enim dolore anim culpa
                                   ullamco laborum. Ut do quis aliqua et in sit ex irure in elit aliquip in. Anim
                                   exercitation ut commodo deserunt non aute et ad occaecat ut magna laborum mollit.
    
    Options:
      -V, --version                output the version number
      --archived <true|false>      define the new archived state of the project
      --budget <budget>            Defines the budget either in minutes or cents, alternatively also a duration value can
                                   be used. F.e. 23:42 for 23 hours and 42 minutes.
      --budget-type <budget_type>  Defines the budget type that should be used. Only accepts one of the following options:
                                   minutes_per_month, minutes, cents, cents_per_month
      --hourly-rate <hourlyRate>   optional value in cents to set for new hourly rate
      --name <name>                Alters the name of the project to the given value
      --note <note>                Alters the note of the project to the given value
      --update-entries             Works only in compbination with hourly-rate. When used also updates all already created
                                   time entries of the project with the new hourly-rate
      -h, --help                   output usage information
    
    
    semver: major 
    opened by Ephigenia 24
  • Added support for option value from environment variables

    Added support for option value from environment variables

    Pull Request

    Problem

    Commander does not have direct support for specifying options coming from environment variables, nor does it initialize options from environment variables.

    Specifying program options via the environment is commonplace for twelve factor apps, particularly those that run in containers. It would be convenient if when specifying program options, we could also specify that those options may be present in the environment.

    Since commander does not include this ability, there are two types of options available. One is to use commander as designed and move the responsibility to the operator (interpolate environment variables onto the command line). Another option is to introduce another pre or post-processing step that handles environment variables in a special way. I have implemented this second option several different ways over the past decade and they all feel hacky.

    Solution

    My approach was to extend the definition of option flags to include an additional flag indicating that an option's value may come via the environment.

    • .option('-c, --context [context], env:CLOUD_CONTEXT', 'specifies an execution context', 'google')
    • .option('-s, --size <size>, env:SHIRT_SIZE', 'shirt size (XS, S, M, L, XL)', 'L')

    If you don't mind reading code, I think the example/options-from-env.js file expresses the change well:

    #!/usr/bin/env node
    
    // This is used as an example in the README for:
    //    Environment variables and options
    //
    // Example output pretending command called pizza-options (or try directly with `node options-from-env.js`)
    //
    // $ DEBUG_LEVEL=verbose pizza-options
    // { DEBUG_LEVEL: 'verbose', small: undefined, pizzaType: undefined }
    // pizza details:
    // $ pizza-options -p
    // error: option '-p, --pizza-type <type>, env:FAVOURITE_PIZZA' argument missing
    // $ DEBUG_LEVEL=info pizza-options -s -p vegetarian
    // { DEBUG_LEVEL=info, small: true, pizzaType: 'vegetarian' }
    // pizza details:
    // - small pizza size
    // - vegetarian
    // $ FAVOURITE_PIZZA=pepperoni pizza-options --small
    // pizza details:
    // - small pizza size
    // - pepperoni
    // $ FAVOURITE_PIZZA=pepperoni pizza-options -s -p cheese
    // pizza details:
    // - small pizza size
    // - cheese
    
    // const commander = require('commander'); // (normal include)
    const commander = require('../'); // include commander in git clone of commander repo
    const program = new commander.Command();
    
    program
      // environment variables can be declared alone
      .option('env:DEBUG_LEVEL', 'debug level from environment')
      .option('-s, --small', 'small pizza size')
      // environment variables are more interesting when they relate to a command line option
      .option('-p, --pizza-type <type>, env:FAVOURITE_PIZZA', 'flavour of pizza');
    
    program.parse(process.argv);
    
    if (program.DEBUG_LEVEL) console.log(program.opts());
    console.log('pizza details:');
    if (program.small) console.log('- small pizza size');
    if (program.pizzaType) console.log(`- ${program.pizzaType}`);
    

    Even though my solution allows environment variables to be declared alone, it becomes much more useful when combined with short and long flags, custom coercion, and default values. All of these continue to work the way they always have, but now, if there is a value present in the environment, it will be (optionally) coerced and will replace the default value, if one is present, as the option's initial value. Subsequently, if the option is also specified by the operator at the the command line, the option specified on the command line takes precedence over the value from the environment.

    This modification does not change the interface/contracts.

    • All tests pass
    • 3 additional tests
    • Two more examples
    • Updated English readme
    • Updated comments in the typings

    The pre-existing feature that toggles bald options, such as -e, --enable when they appear multiple times is non-intuitive when used with environment variables. I wrote a special example examples/options-flag-from-env.js and had to debug for a while to figure out why this special case is so mind-bending. The example bash output clarifies the oddity:

    #!/usr/bin/env node
    
    // Commander toggles flags when they are specified multiple times, this
    // includes when the value is specified via environment variable.
    //
    // When specifying a boolean flag from an environment variable, it is necessary
    // to coerce the value since environment variables are strings.
    //
    // Example output pretending command called toggle (or try directly with `node options-flag-from-env.js`)
    //
    // $ toggle
    // disabled
    // $ toggle -e
    // enabled
    // $ toggle -ee
    // disabled
    // $ ENABLE=t toggle
    // enabled
    // $ ENABLE=t toggle -e
    // disabled
    // $ ENABLE=f toggle --enable
    // enabled
    
    // const commander = require('commander'); // (normal include)
    const commander = require('../'); // include commander in git clone of commander repo
    const program = new commander.Command();
    
    function envBoolCoercion(val, prior) {
      if (val !== undefined) {
        return [true, 1, 'true', 't', 'yes', 'y', 'on'].indexOf(
          typeof val === 'string' ? val.toLowerCase() : val
        ) >= 0;
      }
      return !prior;
    }
    
    program
      .option('-e, --enable, env:ENABLE', 'enables the feature', envBoolCoercion);
    
    program.parse(process.argv);
    
    console.log(program.enable ? 'enabled' : 'disabled');
    

    ChangeLog

    Added support for option value from environment variables

    needs discussion 
    opened by flitbit 23
  • Fixing git style subcommands on Windows & allowing subcommands to come from dependency modules

    Fixing git style subcommands on Windows & allowing subcommands to come from dependency modules

    This PR fixes git style subcommands to work correctly on Windows, and adds logic such that git style subcommands can be inherited from child dependencies, allowing you to break large sets of commands into a multi-repo project. (It should also allow for dynamically varying available subcommands according to what is currently installed under ./node_modules)

    I built a command for managing multi-repo projects, which dogfoods this patch to manage its own repos as well: https://github.com/mateodelnorte/meta/blob/master/package.json#L38-L39. meta, itself, has only one command – meta, which loads all child commands by searching through it's node_modules for matching meta-* modules and registering them via their index.js.

    This all works fine with the current commander.js, but when attempting to call them commander can't locate them. This patch ensures that commander can find the git subcommands and execute them.

    meta --help
    
      Usage: meta [options] [command]
    
    
      Commands:
    
        git         manage your meta repo and child git repositories 
        npm         run npm commands against your meta and child repositories 
        help [cmd]  display help for [cmd]
    
      Options:
    
        -h, --help     output usage information
        -V, --version  output the version number
    

    The git subcommand, above, is provided by https://github.com/mateodelnorte/meta-git. The npm subcommand, above, is provided by https://github.com/mateodelnorte/meta-npm

    needs discussion 
    opened by mateodelnorte 23
  • Improve Command typings

    Improve Command typings

    Pull Request

    Problem

    This is related to #1245, #1585, similar to #1356 that tries to improve the TypeScript writing experiences. Commander and TypeScript have changed a lot, and improving the typings of commander today, to provide more specific type information of given options, has become more feasible.

    Solution

    This PR creates a generic class for each Argument, Option, and Command, and solves the camelCase, .action, .addArgument, .addOption, and .opts problems that blocked #1356. You can try this TS Playground link, scroll to the bottom, hover the variables, make some changes and see if there're some syntax I failed to support.

    opts hover result

    However, there're still some other problems like storeOptionsAsProperties, which is likely able to be solved by intersecting the generics returned with this, but I experienced a huge performance impact when I add that & this to each .argument and .option overload.

    Also, the result of chaining off of commander needs to be assigned to a new variable. This can be improved if one day TS supports Non‑void returning assertion functions.

    Any comment on this?

    ChangeLog

    needs discussion semver: major 
    opened by PaperStrike 22
  • Add a way to override help and version help message

    Add a way to override help and version help message

    Close #47.

    Add override for the help message by calling program.help(message).

    Add override for the version message by calling program.version(version, flag, message);

    opened by idmontie 22
  • Add support for variadic args on options

    Add support for variadic args on options

    Seems pretty obvious to me that is perfectly possible ( and even reasonable) to be able to send a unkown length list of values for an option, and agree that being that the scenario, it could only be applied to last option ( or, optionally, until we find some kind of "terminate" char combo ( "--" would be great, but probably mess with some command shells)

    it's doable?

    enhancement 
    opened by develmts 22
  • Problem while executing action of a command that is called inside action of another command?

    Problem while executing action of a command that is called inside action of another command?

    Action specified for the userCommand will get one more command from user using the readline function. That command is converted to a command array for parsing using the interpreter instance created. But the action for the net is not invoked when the readline reads a command from console . Below is the following code. I want the inner actions for the inner commands specified within a top level command to run .

    const commander = require('commander')
    const readline = require('readline');
    const program = new commander.Command();
    const interpreter = new commander.Command();
    
    const userCommand = program.command('user');
    userCommand
        .action(async() => {
                console.log("inside user")
                var rl = readline.createInterface({
                    input: process.stdin,
                    output: process.stdout
                });
               let waitForUserInput = async() => {
                      rl.question("command > ", async function(command) {
                      if (command == "quit"){
                          rl.close();
                      } else {
                          console.log("command entered is "+command)
                          var commandArr = command.split(" ");
                          const net = interpreter.command('net');
                          net 
                              .command('create')
                              .action(async() => {
                                  console.log("create is success")
                              })
                          net 
                              .command('remove')
                              .action(async() => {
                                  console.log("remove is success")
                              })
                          interpreter.parseAsync(commandArr);
                          await waitForUserInput()
                      }
                });
            }
    await waitForUserInput();
    
         })
    
    opened by PreethiVuchuru27916 4
  • List all command's arguments using Helper

    List all command's arguments using Helper

    I want to list all the arguments (or sub-commands, not sure of the difference) of my command.

    If I look the property _args, I can confirm my command has an argument:

    [
      {
        "description": "",
        "variadic": false,
        "required": false,
        "_name": "commands"
      }
    ]
    
    Screenshot of the Argument object image

    To not use a private property, I try to access this argument with the Help class and the visibleArguments method (see the code)

    The problem, I do not have any description for my argument and the implementation of visibleArguments requires one.

    Is this a problem? If not, can someone explain it to me? Is there any other clean way?

    Thank you! 😁

    opened by grallm 6
  • Wrapping the second and following line in a multiline description doesn't work if the line starts from space

    Wrapping the second and following line in a multiline description doesn't work if the line starts from space

    I wanted to add an indent to the second line in the description.

    program
      .option('--config <path>', 'Configuration file path')
      .option(
        '-M, --message-pattern <RegExp>',
        `Message pattern to configure where JIRA ticket number will be inserted
        * Symbols '$J' 
        * Symbols '$M' `,
      );
    

    I've expected something like this

    Usage: index [options]   
                                           
    Options:                          
      --config <path>                 Configuration file path
      -M, --message-pattern <RegExp>  Message pattern to configure where JIRA ticket number will be inserted
                                         * Symbols `$J` 
                                         * Symbols `$M`
      -h, --help                      display help for command         
    

    But got:

    Usage: index [options]   
                                           
    Options:                          
      --config <path>                 Configuration file path
      -M, --message-pattern <RegExp>  Message pattern to configure where JIRA ticket number will be inserted
          * Symbols '$J'
          * Symbols '$M'
      -h, --help                      display help for command  
    

    I tried to change the template literal to a string but got the same result.

    program
      .option('--config <path>', 'Configuration file path')
      .option(
        '-M, --message-pattern <RegExp>',
        'Message pattern to configure where JIRA ticket number will be inserted\n' +
        '   * Symbols `$J`\n' +
        '   * Symbols `$M`',
     // ↑ three spaces
      );
    

    But if I remove leading spaces from the second and third line, the indent will work correctly;

    Usage: index [options]
    
    Options:
      --config <path>                 Configuration file path
      -M, --message-pattern <RegExp>  Message pattern to configure where JIRA ticket number will be inserted
                                      * Symbols `$J`
                                      * Symbols `$M`
      -h, --help                      display help for command
    
    docs 
    opened by bk201- 2
  • Add support for built-in translations and author supplied strings

    Add support for built-in translations and author supplied strings

    Pull Request

    Problem

    People want to modify or translate the built-in error messages and help section titles.

    See: #128 #486 #774 #1498 #1608 #1801

    We do already have individual support for modifying the help option, and help command name and description, and version option.

    Solution

    Add translation support for the error messages and help related strings. Use tagged string templates as suggested in #1801, which preserves the existing message generation.

    Add:

    • program.configureStrings(strings) for author to supply their own strings
    • program.locale(localeName) to load built-in translation
    • locale for zh-CN thanks to @gylove1994

    Currently includes some partial translations using strings from yargs (locales/*-x-partial), partly to encourage full translations, partly as an experiment to fill out the locales folder and get a feel for what it could be like.

    Technical note: node 12 does not include the full ICU and the Intl.ListFormat support falls back to default for non-English on at least some platforms. However, the next version of Commander will be dropping node 12 and later versions do have full ICU and get consistent behaviour with node 14, 16, and 18. (The list formatting is not critical, but nice to do it an official way.)

    Implementation notes:

    • Leaving I18n private for now so can easily make changes. Adding the functionality on Command rather than exposing the lower-level building blocks.
    • only offering manual selection of locale for now (not automatic)
      • authors supporting multiple languages with their own strings can do their own auto-detection
      • not sure how to do good auto-detection on Windows

    ChangeLog

    semver: major 
    opened by shadowspawn 2
  • Mark options as required together

    Mark options as required together

    I have a use case where I could like to require my command options to be conditionally required, and exclusive. For example, let's say my testing command has three options:

    • -x, --one <number>
    • -y, --two <number>
    • -z, --three <number>

    I'd like to make it where the command either needs -x provided or both -y and -z together. The .conflicts() support makes it easy to ensure that they aren't used together where they shouldn't be but there doesn't seem to be a way to mark -x as required when -y and/or -z isn't used, nor is there a way to mark it such that both -y and -z must be used in combination together when -x isn't used.

    I could craft a way to do this myself, and I've searched the project to see if this has been discussed before, but I can't find anything.

    enhancement needs discussion 
    opened by whitlockjc 2
  • Add localization method to Command

    Add localization method to Command

    Even though we can use .configureOutput() to configure the output to change the help header and error, but it is not convenient for user to change it entirely ( include error message and help header and etc. ) for localization.

    I want to add a method to Command like program.localization('zh_CN') to change the output template words and error message could be Simplified Chinese entirely.

    If it is passable to add , I will try to make a PR then.

    Related Issues: #128 #774 #1608

    Edit from @shadowspawn to readers: please 👍 this comment if you would like localisation support and support for customising strings added to Commander. You don't need to read all the comments!

    enhancement 
    opened by gylove1994 30
Releases(v9.5.0)
  • v9.5.0(Jan 7, 2023)

  • v9.4.1(Sep 30, 2022)

    Fixed

    • .setOptionValue() now also clears option source (#1795)
    • TypeScript: add implied to OptionValueSource for option values set by using .implies() (#1794)
    • TypeScript : add undefined to return type of .getOptionValueSource() (#1794)

    Changed

    • additions to README
    Source code(tar.gz)
    Source code(zip)
  • v9.4.0(Jul 15, 2022)

    Added

    • preSubcommand hook called before direct subcommands (#1763)

    Fixed

    • export InvalidOptionArgumentError in esm (#1756)

    Changed

    • update dependencies (#1767)
    Source code(tar.gz)
    Source code(zip)
  • v9.3.0(May 28, 2022)

    Added

    • .summary() for a short summary to use instead of description when listing subcommands in help (#1726)
    • Option.implies() to set other option values when the option is specified (#1724)
    • updated Chinese README with 9.x changes (#1727)

    Fixed

    • TypeScript: add string[] to .options() default value parameter type for use with variadic options (#1721)

    Deprecated

    • multi-character short option flag (e.g. -ws) (#1718)
    Source code(tar.gz)
    Source code(zip)
  • v9.2.0(Apr 15, 2022)

    Added

    • conditional export of 'types' for upcoming TypeScript module resolution (#1703)
    • example file showing two ways to add global options to subcommands (#1708)

    Fixed

    • detect option conflicts in parent commands of called subcommand (#1710)

    Changed

    • replace deprecated String.prototype.substr (#1706)
    Source code(tar.gz)
    Source code(zip)
  • v9.1.0(Mar 18, 2022)

    Added

    • Option .conflicts() to set conflicting options which can not be specified together (#1678)
    • (developer) CodeQL configuration for GitHub Actions (#1698)
    Source code(tar.gz)
    Source code(zip)
  • v9.0.0(Jan 29, 2022)

    Added

    • simpler ECMAScript import (#1589)
    • Option.preset() allows specifying value/arg for option when used without option-argument (especially optional, but also boolean option) (#1652)
    • .executableDir() for custom search for subcommands (#1571)
    • throw with helpful message if pass Option to .option() or .requiredOption() (#1655)
    • .error() for generating errors from client code just like Commander generated errors, with support for .configureOutput (), .exitOverride(), and .showHelpAfterError() (#1675)
    • .optsWithGlobals() to return merged local and global options (#1671)

    Changed

    • Breaking: Commander 9 requires Node.js v12.20.0 or higher
    • update package-lock.json to lockfile@2 format (#1659)
    • showSuggestionAfterError is now on by default (#1657)
    • Breaking: default value specified for boolean option now always used as default value (see .preset() to match some previous behaviours) (#1652)
    • default value for boolean option only shown in help if true/false (#1652)
    • use command name as prefix for subcommand stand-alone executable name (with fallback to script name for backwards compatibility) (#1571)
    • allow absolute path with executableFile (#1571)
    • removed restriction that nested subcommands must specify executableFile (#1571)
    • TypeScript: allow passing readonly string array to .choices() (#1667)
    • TypeScript: allow passing readonly string array to .parse(), .parseAsync(), .aliases() (#1669)

    Fixed

    • option with optional argument not supplied on command line now works when option already has a value, whether from default value or from previous arguments (#1652)

    Removed

    • Breaking: removed internal fallback to require.main.filename when script not known from arguments passed to .parse() (can supply details using .name(), and .executableDir() or executableFile) (#1571)
    Source code(tar.gz)
    Source code(zip)
  • v9.0.0-1(Jan 14, 2022)

    Added

    • .error() for generating errors from client code just like Commander generated errors, with support for .configureOutput(), .exitOverride(), and .showHelpAfterError() (#1675)
    • .optsWithGlobals() to return merged local and global options (#1671)
    Source code(tar.gz)
    Source code(zip)
  • v9.0.0-0(Dec 22, 2021)

    Added

    • simpler ECMAScript import (#1589)
    • Option.preset() allows specifying value/arg for option when used without option-argument (especially optional, but also boolean option) (#1652)
    • .executableDir() for custom search for subcommands (#1571)
    • throw with helpful message if pass Option to .option() or .requiredOption() (#1655)

    Changed

    • Breaking: Commander 9 requires Node.js v12.20.0 or higher
    • update package-lock.json to lockfile@2 format (#1659)
    • showSuggestionAfterError is now on by default (#1657)
    • Breaking: default value specified for boolean option now always used as default value (see .preset() to match some previous behaviours) (#1652)
    • default value for boolean option only shown in help if true/false (#1652)
    • use command name as prefix for subcommand stand-alone executable name (with fallback to script name for backwards compatibility) (#1571)
    • allow absolute path with executableFile (#1571)
    • removed restriction that nested subcommands must specify executableFile (#1571)

    Fixed

    • option with optional argument not supplied on command line now works when option already has a value, whether from default value or from previous arguments (#1652)

    Removed

    • Breaking: removed internal fallback to require.main.filename when script not known from arguments passed to .parse() (can supply details using .name(), and .executableDir() or executableFile) (#1571)
    Source code(tar.gz)
    Source code(zip)
  • v8.3.0(Oct 22, 2021)

    Added

    • .getOptionValueSource() and .setOptionValueWithSource(), where expected values for source are one of 'default', 'env', 'config', 'cli' (#1613)

    Deprecated

    • .command('*'), use default command instead (#1612)
    • on('command:*'), use .showSuggestionAfterError() instead (#1612)
    Source code(tar.gz)
    Source code(zip)
  • v8.2.0(Sep 10, 2021)

    Added

    • .showSuggestionAfterError() to show suggestions after unknown command or unknown option (#1590)
    • add Option support for values from environment variables using .env() (#1587)

    Changed

    • show error for unknown global option before subcommand (rather than just help) (#1590)

    Removed

    • TypeScript declaration of unimplemented Option method argumentRejected
    Source code(tar.gz)
    Source code(zip)
  • v8.1.0(Jul 27, 2021)

    Added

    • .copyInheritedSettings() (#1557)
    • update Chinese translations for Commander v8 (#1570)
    • Argument methods for .argRequired() and .argOptional() (#1567)
    Source code(tar.gz)
    Source code(zip)
  • v8.0.0(Jun 25, 2021)

    Added

    • .argument(name, description) for adding command-arguments (#1490)
      • supports default value for optional command-arguments (#1508)
      • supports custom processing function (#1508)
    • .createArgument() factory method (#1497)
    • .addArgument() (#1490)
    • Argument supports .choices() (#1525)
    • .showHelpAfterError() to display full help or a custom message after an error (#1534)
    • .hook() with support for 'preAction' and 'postAction' callbacks (#1514)
    • client typing of .opts() return type using TypeScript generics (#1539)
    • the number of command-arguments is checked for programs without an action handler (#1502)
    • .getOptionValue() and .setOptionValue() (#1521)

    Changed

    • refactor and simplify TypeScript declarations (with no default export) (#1520)
    • .parseAsync() is now declared as async (#1513)
    • Breaking: Help method .visibleArguments() returns array of Argument (#1490)
    • Breaking: Commander 8 requires Node.js 12 or higher (#1500)
    • Breaking: CommanderError code commander.invalidOptionArgument renamed commander.invalidArgument (#1508)
    • Breaking: TypeScript declaration for .addTextHelp() callback no longer allows result of undefined, now just string (#1516)
    • refactor index.tab into a file per class (#1522)
    • remove help suggestion from "unknown command" error message (see .showHelpAfteError()) (#1534)
    • Command property .arg initialised to empty array (was previously undefined) (#1529)
    • update dependencies

    Deprecated

    • second parameter of cmd.description(desc, argDescriptions) for adding argument descriptions (#1490)
      • (use new .argument(name, description) instead)
    • InvalidOptionArgumentError (replaced by InvalidArgumentError) (#1508)

    Removed

    • Breaking: TypeScript declaration for default export of global Command object (#1520)
      • (still available as named program export)

    Migration Tips

    If you have a simple program without an action handler, you will now get an error if there are missing command-arguments.

    program
      .option('-d, --debug')
      .arguments('<file>');
    program.parse();
    
    $ node trivial.js 
    error: missing required argument 'file'
    

    If you want to show the help in this situation, you could check the arguments before parsing:

    if (process.argv.length === 2)
      program.help();
    program.parse();
    

    Or, you might choose to show the help after any user error:

    program.showHelpAfterError();
    
    Source code(tar.gz)
    Source code(zip)
  • v8.0.0-2(Jun 6, 2021)

    Added

    • .showHelpAfterError() to display full help or a custom message after an error (#1534)
    • custom argument processing function also called without action handler (only with action handler in v8.0.0-0) (#1529)

    Changed

    • remove help suggestion from "unknown command" error message (see .showHelpAfteError()) (#1534)
    • Command property .arg initialised to empty array (was previously undefined) (#1529)
    Source code(tar.gz)
    Source code(zip)
  • v8.0.0-1(May 31, 2021)

    Added

    • .addArgument() (#1490)
    • Argument supports .choices() (#1525)
    • client typing of .opts() return type using TypeScript generics (#1539)

    Changed

    • refactor index.tab into a file per class (#1522)
    • update dependencies
    Source code(tar.gz)
    Source code(zip)
  • v8.0.0-0(May 22, 2021)

    Added

    • .getOptionValue() and .setOptionValue() (#1521)
    • .hook() with support for 'preAction' and 'postAction' callbacks (#1514)
    • .argument(name, description) for adding command-arguments (#1490)
      • supports default value for optional command-arguments (#1508)
      • supports custom processing function (#1508)
    • .createArgument() factory method (#1497)
    • the number of command-arguments is checked for programs without an action handler (#1502)

    Changed

    • refactor and simplify TypeScript declarations (with no default export) (#1520)
    • .parseAsync() is now declared as async (#1513)
    • Breaking: Help method .visibleArguments() returns array of Argument (#1490)
    • Breaking: Commander 8 requires Node.js 12 or higher (#1500)
    • Breaking: CommanderError code commander.invalidOptionArgument renamed commander.invalidArgument (#1508)
    • Breaking: TypeScript declaration for .addTextHelp() callback no longer allows result of undefined, now just string (#1516)

    Deprecated

    • second parameter of cmd.description(desc, argDescriptions) for adding argument descriptions (#1490)
      • (use new .argument(name, description) instead)
    • InvalidOptionArgumentError (replaced by InvalidArgumentError) (#1508)

    Removed

    • Breaking: TypeScript declaration for default export of global Command object (#1520)
      • (still available as named program export)
    Source code(tar.gz)
    Source code(zip)
  • v7.2.0(Mar 21, 2021)

    Added

    • TypeScript typing for parent property on Command (#1475)
    • TypeScript typing for .attributeName() on Option (#1483)
    • support information in package (#1477)

    Changed

    • improvements to error messages, README, and tests
    • update dependencies
    Source code(tar.gz)
    Source code(zip)
  • v7.1.0(Feb 15, 2021)

    Added

    • support for named imports from ECMAScript modules (#1440)
    • add .cjs to list of expected script file extensions (#1449)
    • allow using option choices and variadic together (#1454)

    Fixed

    • replace use of deprecated process.mainModule (#1448)
    • regression for legacy command('*') and call when command line includes options (#1464)
    • regression for on('command:*', ...) and call when command line includes unknown options (#1464)
    • display best error for combination of unknown command and unknown option (i.e. unknown command) (#1464)

    Changed

    • make TypeScript typings tests stricter (#1453)
    • improvements to README and tests
    Source code(tar.gz)
    Source code(zip)
  • v7.0.0(Jan 15, 2021)

    Added

    • .enablePositionalOptions() to let program and subcommand reuse same option (#1427)
    • .passThroughOptions() to pass options through to other programs without needing -- (#1427)
    • .allowExcessArguments(false) to show an error message if there are too many command-arguments on command line for the action handler (#1409)
    • .configureOutput() to modify use of stdout and stderr or customise display of errors (#1387)
    • use .addHelpText() to add text before or after the built-in help, for just current command or also for all subcommands (#1296)
    • enhance Option class (#1331)
      • allow hiding options from help
      • allow restricting option arguments to a list of choices
      • allow setting how default value is shown in help
    • .createOption() to support subclassing of automatically created options (like .createCommand()) (#1380)
    • refactor the code generating the help into a separate public Help class (#1365)
      • support sorting subcommands and options in help
      • support specifying wrap width (columns)
      • allow subclassing Help class
      • allow configuring Help class without subclassing

    Changed

    • Breaking: options are stored safely by default, not as properties on the command (#1409)
      • this especially affects accessing options on program, use program.opts()
      • revert behaviour with .storeOptionsAsProperties()
    • Breaking: action handlers are passed options and command separately (#1409)
    • deprecated callback parameter to .help() and .outputHelp() (removed from README) (#1296)
    • Breaking: errors now displayed using process.stderr.write() instead of console.error()
    • deprecate .on('--help') (removed from README) (#1296)
    • initialise the command description to empty string (previously undefined) (#1365)
    • document and annotate deprecated routines (#1349)

    Fixed

    • wrapping bugs in help (#1365)
      • first line of command description was wrapping two characters early
      • pad width calculation was not including help option and help command
      • pad width calculation was including hidden options and commands
    • improve backwards compatibility for custom command event listeners (#1403)

    Deleted

    • Breaking: .passCommandToAction() (#1409)
      • no longer needed as action handler is passed options and command
    • Breaking: "extra arguments" parameter to action handler (#1409)
      • if being used to detect excess arguments, there is now an error available by setting .allowExcessArguments(false)

    Migration Tips

    The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.

    If you wish to restore the old behaviour and get running quickly you can call .storeOptionsAsProperties(). To allow you to move to the new code patterns incrementally, the action handler will be passed the command twice, to match the new "options" and "command" parameters (see below).

    program options

    Use the .opts() method to access the options. This is available on any command but is used most with the program.

    program.option('-d, --debug');
    program.parse();
    // Old code before Commander 7
    if (program.debug) console.log(`Program name is ${program.name()}`);
    
    // New code
    const options = program.opts();
    if (options.debug) console.log(`Program name is ${program.name()}`);
    

    action handler

    The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you only accessed the options there may be no code changes required.

    program
      .command('compress <filename>')
      .option('-t, --trace')
      // Old code before Commander 7
      .action((filename, cmd) => {
        if (cmd.trace) console.log(`Command name is ${cmd.name()}`);
      });
    
      // New code
      .action((filename, options, command) => {
        if (options.trace) console.log(`Command name is ${command.name()}`);
      });
    

    If you already set .storeOptionsAsProperties(false) you may still need to adjust your code.

    program
      .command('compress <filename>')
      .storeOptionsAsProperties(false)
      .option('-t, --trace')
      // Old code before Commander 7
      .action((filename, command) => {
        if (command.opts().trace) console.log(`Command name is ${command.name()}`);
      });
    
       // New code
       .action((filename, options, command) => {
          if (command.opts().trace) console.log(`Command name is ${command.name()}`);
       });
    
    Source code(tar.gz)
    Source code(zip)
  • v7.0.0-2(Dec 14, 2020)

    Changed

    • Breaking: options are stored safely by default, not as properties on the command (#1409)
      • this especially affects accessing options on program, use program.opts()
      • revert behaviour with .storeOptionsAsProperties()
    • Breaking: action handlers are passed options and command separately (#1409)

    Added

    • Breaking: error message if there are too many command-arguments on command line for the action handler (#1409)
      • if should be allowed then declare extra arguments, or use .allowExcessArguments()

    Deleted

    • Breaking: .passCommandToAction() (#1409)
      • no longer needed as action handler is passed options and command
    • Breaking: "extra arguments" parameter to action handler (#1409)
      • if being used to detect excess arguments, there is now an error displayed by default

    Migration Tips

    The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.

    If you wish to restore the old behaviour and get running quickly you can call .storeOptionsAsProperties(). To allow you to move to the new code patterns incrementally, the action handler will be passed the command twice, to match the new "options" and "command" parameters (see below).

    program options

    Use the .opts() method to access the options. This is available on any command but is used most with the program.

    program.option('-d, --debug');
    program.parse();
    // Old code before Commander 7
    if (program.debug) console.log(`Program name is ${program.name()}`);
    
    // New code
    const options = program.opts();
    if (options.debug) console.log(`Program name is ${program.name()}`);
    

    action handler

    The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you only accessed the options there may be no code changes required.

    program
      .command('compress <filename>')
      .option('-t, --trace')
      // Old code before Commander 7
      .action((filename, cmd)) => {
        if (cmd.trace) console.log(`Command name is ${cmd.name()}`);
      });
    
      // New code
      .action((filename, options, command)) => {
        if (options.trace) console.log(`Command name is ${command.name()}`);
      });
    

    If you already set .storeOptionsAsProperties(false) you may still need to adjust your code.

    program
      .command('compress <filename>')
      .storeOptionsAsProperties(false)
      .option('-t, --trace')
      // Old code before Commander 7
      .action((filename, command)) => {
        if (command.opts().trace) console.log(`Command name is ${command.name()}`);
      });
    
       // New code
       .action((filename, options, command)) => {
          if (command.opts().trace) console.log(`Command name is ${command.name()}`);
       });
    
    Source code(tar.gz)
    Source code(zip)
  • v6.2.1(Dec 14, 2020)

  • v7.0.0-1(Nov 21, 2020)

    Added

    • .createOption() to support subclassing of automatically created options (like .createCommand()) (#1380)
    • .configureOutput() to modify use of stdout and stderr or customise display of errors (#1387)

    Breaking changes relative to 7.0.0-0

    • rework new Help.wrap() for simpler usage pattern (#1395)
    • rename new "columns" properties (#1396)
      • Help.columns -> helpWidth
      • getOutColumns() -> getOutHelpWidth()
      • getErrColumns() -> getErrHelpWidth()
    Source code(tar.gz)
    Source code(zip)
  • v7.0.0-0(Oct 25, 2020)

    Added

    • use .addHelpText() to add text before or after the built-in help, for just current command or also for all subcommands (#1296)
    • enhance Option class (#1331)
      • allow hiding options from help
      • allow restricting option arguments to a list of choices
      • allow setting how default value is shown in help
    • refactor the code generating the help into a separate public Help class (#1365)
      • support sorting subcommands and options in help
      • support specifying wrap width (columns)
      • allow subclassing Help class
      • allow configuring Help class without subclassing

    Fixed

    • wrapping bugs in help (#1365)
      • first line of command description was wrapping two characters early
      • pad width calculation was not including help option and help command
      • pad width calculation was including hidden options and commands

    Changed

    • document and annotate deprecated routines (#1349)
    • deprecated callback parameter to .help() and .outputHelp() (removed from README) (#1296)
    • deprecate .on('--help') (removed from README) (#1296)
    • initialise the command description to empty string (previously undefined) (#1365)
    Source code(tar.gz)
    Source code(zip)
  • v6.2.0(Oct 25, 2020)

    Added

    • added 'tsx' file extension for stand-alone executable subcommands (#1368)
    • documented second parameter to .description() to describe command arguments (#1353)
    • documentation of special cases with options taking varying numbers of option-arguments (#1332)
    • documentation for terminology (#1361)

    Fixed

    • add missing TypeScript definition for `.addHelpCommand()' (#1375)
    • removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" (#1360)

    Changed

    • update dependencies
    Source code(tar.gz)
    Source code(zip)
  • v6.1.0(Aug 28, 2020)

    Added

    • include URL to relevant section of README for error for potential conflict between Command properties and option values (#1306)
    • .combineFlagAndOptionalValue(false) to ease upgrade path from older versions of Commander (#1326)
    • allow disabling the built-in help option using .helpOption(false) (#1325)
    • allow just some arguments in argumentDescription to .description() (#1323)

    Changed

    • tidy async test and remove lint override (#1312)

    Fixed

    • executable subcommand launching when script path not known (#1322)
    Source code(tar.gz)
    Source code(zip)
  • v6.0.0(Jul 19, 2020)

    Added

    • add support for variadic options (#1250)
    • allow options to be added with just a short flag (#1256)
      • Breaking the option property has same case as flag. e.g. flag -n accessed as opts().n (previously uppercase)
    • Breaking throw an error if there might be a clash between option name and a Command property, with advice on how to resolve (#1275)

    Fixed

    • Options which contain -no- in the middle of the option flag should not be treated as negatable. (#1301)
    Source code(tar.gz)
    Source code(zip)
  • v6.0.0-0(Jun 20, 2020)

    Added

    • add support for variadic options (#1250)
    • allow options to be added with just a short flag (#1256)
    • throw an error if there might be a clash between option name and a Command property, with advice on how to resolve (#1275)
    Source code(tar.gz)
    Source code(zip)
  • v5.1.0(Apr 25, 2020)

    Added

    • support for multiple command aliases, the first of which is shown in the auto-generated help (#531, #1236)
    • configuration support in addCommand() for hidden and isDefault (#1232)

    Fixed

    • omit masked help flags from the displayed help (#645, #1247)
    • remove old short help flag when change help flags using helpOption (#1248)

    Changed

    • remove use of arguments to improve auto-generated help in editors (#1235)
    • rename .command() configuration noHelp to hidden (but not remove old support) (#1232)
    • improvements to documentation
    • update dependencies
    • update tested versions of node
    • eliminate lint errors in TypeScript (#1208)
    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Mar 14, 2020)

    Added

    • support for nested commands with action-handlers (#1 #764 #1149)
    • .addCommand() for adding a separately configured command (#764 #1149)
    • allow a non-executable to be set as the default command (#742 #1149)
    • implicit help command when there are subcommands (previously only if executables) (#1149)
    • customise implicit help command with .addHelpCommand() (#1149)
    • display error message for unknown subcommand, by default (#432 #1088 #1149)
    • display help for missing subcommand, by default (#1088 #1149)
    • combined short options as single argument may include boolean flags and value flag and value (e.g. -a -b -p 80 can be written as -abp80) (#1145)
    • .parseOption() includes short flag and long flag expansions (#1145)
    • .helpInformation() returns help text as a string, previously a private routine (#1169)
    • .parse() implicitly uses process.argv if arguments not specified (#1172)
    • optionally specify where .parse() arguments "from", if not following node conventions (#512 #1172)
    • suggest help option along with unknown command error (#1179)
    • TypeScript definition for commands property of Command (#1184)
    • export program property (#1195)
    • createCommand factory method to simplify subclassing (#1191)

    Fixed

    • preserve argument order in subcommands (#508 #962 #1138)
    • do not emit command:* for executable subcommands (#809 #1149)
    • action handler called whether or not there are non-option arguments (#1062 #1149)
    • combining option short flag and value in single argument now works for subcommands (#1145)
    • only add implicit help command when it will not conflict with other uses of argument (#1153 #1149)
    • implicit help command works with command aliases (#948 #1149)
    • options are validated whether or not there is an action handler (#1149)

    Changed

    • Breaking .args contains command arguments with just recognised options removed (#1032 #1138)
    • Breaking display error if required argument for command is missing (#995 #1149)
    • tighten TypeScript definition of custom option processing function passed to .option() (#1119)
    • Breaking .allowUnknownOption() (#802 #1138)
      • unknown options included in arguments passed to command action handler
      • unknown options included in .args
    • only recognised option short flags and long flags are expanded (e.g. -ab or --foo=bar) (#1145)
    • Breaking .parseOptions() (#1138)
      • args in returned result renamed operands and does not include anything after first unknown option
      • unknown in returned result has arguments after first unknown option including operands, not just options and values
    • Breaking .on('command:*', callback) and other command events passed (changed) results from .parseOptions, i.e. operands and unknown (#1138)
    • refactor Option from prototype to class (#1133)
    • refactor Command from prototype to class (#1159)
    • changes to error handling (#1165)
      • throw for author error, not just display message
      • preflight for variadic error
      • add tips to missing subcommand executable
    • TypeScript fluent return types changed to be more subclass friendly, return this rather than Command (#1180)
    • .parseAsync returns Promise<this> to be consistent with .parse() (#1180)
    • update dependencies

    Removed

    • removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on @types/node (#1146)
    • removed private function normalize (the functionality has been integrated into parseOptions) (#1145)
    • parseExpectedArgs is now private (#1149)

    Migration Tips

    If you use .on('command:*') or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour.

    If you use program.args or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour.

    If you use .command('*') to add a default command, you may be be able to switch to isDefault:true with a named command.

    Source code(tar.gz)
    Source code(zip)
  • v5.0.0-4(Mar 3, 2020)

Owner
TJ Holowaychuk
TJ Holowaychuk
a simple zero-configuration command-line http server

http-server: a command-line http server http-server is a simple, zero-configuration command-line http server. It is powerful enough for production usa

http ... PARTY! 12.4k Jan 4, 2023
Control the macOS dark mode from the command-line

dark-mode Control the macOS dark mode from the command-line Requires macOS 10.10 or later. macOS 10.13 or earlier needs to download the Swift runtime

Sindre Sorhus 630 Dec 30, 2022
🌈 React for interactive command-line apps

React for CLIs. Build and test your CLI output using components. Ink provides the same component-based UI building experience that React offers in the

Vadim Demedes 19.7k Jan 9, 2023
Pretty unicode tables for the command line

cli-table3 This utility allows you to render unicode-aided tables on the command line from your node.js scripts. cli-table3 is based on (and api compa

null 418 Dec 28, 2022
Control the Plash app from the command-line

plash-cli Control the Plash app from the command-line Install $ npm install --global plash Requires Node.js 14 or later. Requires Plash 2.3.0 or late

Sindre Sorhus 33 Dec 30, 2022
A C++ based command-line (CLI) program that lets you manage your tasks

COMMAND LINE INTERFACE TODO APP a command-line (CLI) program that lets you manage your tasks. The specification for this project is written down as te

Rahul Prabhakar 1 Dec 25, 2021
Close chrome tabs from command-line (macOS only)

Close-tab Read all tabs from an activated window of the chrome, open with vi prompt, you can close tabs by deleting lines. Istallation npm install -g

Karl Saehun Chung 8 Jun 18, 2022
1History is a command line tool to backup your histories of different browsers into one place

1History All your history in one place. 1History is a command line tool to backup your histories of different browsers into one place. Features Suppor

null 340 Dec 31, 2022
Wordle and Termooo style classic word guessing game for the command line. One new word per day!

Wordle and Termooo style classic word guessing game for the command line. One new word per day!

Anderson Silva 3 Nov 27, 2022
SFDX Plugin to set Email Deliverability Access Level for an org easily and quickly via command line interface

SFDX Plugin to set Email Deliverability Access Level for an org easily and quickly via command line interface

Max Goldfarb 11 Dec 16, 2022
A project for FAST command line interface tools.

FAST CLI Project This is the FAST CLI project, containing the FAST CLI package and other related CLI packages for FAST project creation and management

Microsoft 24 Dec 5, 2022
A command line interface for programmatically creating data silos on app.transcend.io

Table of Contents Overview Installation Authentication transcend.yml Usage tr-pull tr-push CI Integration Dynamic Variables tr-scan Overview A command

Transcend 15 Dec 13, 2022
Autify Command Line Interface (CLI)

Autify Command Line Interface (CLI) Autify CLI can help your integration with Autify! Autify Command Line Interface (CLI) Usage Commands Usage Note: n

Autify 36 Jan 2, 2023
Windows command line tool to block outbound connections for files within a directory.

fwg A Windows command line tool to block outbound connections for files within a directory. fwg utilizes the power of PowerShell and Windows Network S

raymond wang 3 Jul 19, 2022
The command-line interface for versum

@versumstudios/cli The command-line interface for versum. versum-cli Usage Contributing How to use Export Templates Usage To install the latest versio

Versum Studios 8 Nov 3, 2022
LinkFree CLI is a command line tool that helps you to create your LinkFree profile through CLI.

LinkFree CLI LinkFree CLI is a command line tool that helps you to create your LinkFree profile through CLI. Demo Using the CLI (Commands) Note First

Pradumna Saraf 32 Dec 26, 2022
Run a command when a certain file exists, and/or watch files to rerun on changes

Run a command when a certain file exists, and/or watch files to rerun on changes

EGOIST 45 Sep 23, 2022
CLI Command for Two Factor Authentication.🚀

CLI Command for Two Factor Authentication.??

Yuga Sun 7 Nov 5, 2022
A small Discord moderation bot, without a command handler

A small Discord moderation bot, without a command handler Getting started (Add Star ⭐ <3) ?? Requirements Node.js A code editor (visual studio code, a

null 10 Mar 12, 2022