### Custom Help Text Example Output Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates the resulting help output after adding custom text using 'addHelpText'. The custom 'Example call' section is appended to the default help information. ```text Usage: custom-help [options] Options: -f, --foo enable some foo -h, --help display help for command Example call: $ custom-help --help ``` -------------------------------- ### Install Commander.js Source: https://github.com/tj/commander.js/blob/master/Readme.md Install Commander.js using npm. This is the first step to using the library in your Node.js project. ```sh npm install commander ``` -------------------------------- ### Custom Option Processing Examples Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates the output of various custom option processing functions with different command-line inputs. ```console $ 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' ] ``` -------------------------------- ### Example of command line argument structure Source: https://github.com/tj/commander.js/blob/master/docs/terminology.md Demonstrates the arrangement of commands, options, option-arguments, and command-arguments in a single command line string. ```sh my-utility command -o --option option-argument command-argument-1 command-argument-2 ``` -------------------------------- ### Variadic Options Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates how to define variadic options using '...' in the placeholder. Parsed values become arrays. Option arguments are read until a dash-prefixed argument or '--' is encountered. ```javascript program .option('-n, --number ', 'specify numbers') .option('-l, --letter [letters...]', 'specify letters'); program.parse(); console.log('Options: ', program.opts()); console.log('Remaining arguments: ', program.args); ``` -------------------------------- ### Custom Version Option Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows how to customize the version option flags and description by passing additional parameters to the `.version()` method. ```javascript program.version('0.0.1', '-v, --vers', 'output the current version'); ``` -------------------------------- ### Default Option Value Examples Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows the output when an option with a default value is not provided and when it is provided with a specific value. ```console $ pizza-options cheese: blue $ pizza-options --cheese stilton cheese: stilton ``` -------------------------------- ### Negatable Option Examples Source: https://github.com/tj/commander.js/blob/master/Readme.md Illustrates the behavior of negatable options, including default states and explicit usage to remove or set options. ```console $ 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 ``` -------------------------------- ### Boolean or Optional Value Option Examples Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows how the option behaves when used as a boolean flag, with an optional value, or not provided at all. ```console $ pizza-options no cheese $ pizza-options --cheese add cheese $ pizza-options --cheese mozzarella add cheese type mozzarella ``` -------------------------------- ### Defining Program Options Source: https://github.com/tj/commander.js/blob/master/Readme.md Example of defining various types of options including those with arguments, boolean flags, and custom names. Demonstrates short and long flag formats. ```javascript program .option('-p, --port ', 'server port number') .option('--trace', 'add extra debugging output') .option('--ws, --workspace ', 'use a custom workspace') ``` -------------------------------- ### Command-line Execution Examples Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Illustrates how Commander.js parses combined short options, including cases where an option takes an argument and when multiple boolean-like options are combined. ```bash $ collect -o 3 other servings: 3 $ collect -o3 other servings: 3 $ collect -l -v vegan servings: true halal servings: true $ collect -lv # oops halal servings: v ``` ```console $ collect -a -v -l any servings: true vegan servings: true halal servings: true ``` -------------------------------- ### Version Option Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Adds a default version option (-V, --version) to the program. When invoked, it displays the version number and exits. ```javascript program.version('0.0.1'); ``` -------------------------------- ### Variadic Options Console Output Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows the output of the variadic options example with different command-line inputs, illustrating how arguments are parsed into arrays. ```console $ 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' ] ``` -------------------------------- ### Required Option Error Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates the error message displayed when a required option is not specified on the command line. ```console $ pizza error: required option '-c, --cheese ' not specified ``` -------------------------------- ### Define Options with Arguments Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Define multiple short options that can take an optional argument. This setup allows for options like '-o 3' or '-o3'. ```javascript program .name('collect') .option("-o, --other [count]", "other serving(s)") .option("-v, --vegan [count]", "vegan serving(s)") .option("-l, --halal [count]", "halal serving(s)"); program.parse(process.argv); const opts = program.opts(); if (opts.other) console.log(`other servings: ${opts.other}`); if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`); if (opts.halal) console.log(`halal servings: ${opts.halal}`); ``` -------------------------------- ### Add Custom Help Text After Built-in Help Source: https://github.com/tj/commander.js/blob/master/Readme.md Extend the auto-generated help message by adding custom text. The 'after' position inserts the provided text after the standard options and usage information. This example adds an example call to the help output. ```javascript program .option('-f, --foo', 'enable some foo'); program.addHelpText('after', ` Example call: $ custom-help --help`); ``` -------------------------------- ### Advanced Options Conflict Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Illustrates the error message when conflicting options are used together, as defined by the `.conflicts()` method. ```console $ extra --disable-server --port 8000 error: option '--disable-server' cannot be used with option '-p, --port ' ``` -------------------------------- ### Configure Custom Output Streams Source: https://github.com/tj/commander.js/blob/master/Readme.md Customize Commander's output handling by overriding write routines for standard output and error, and by customizing error message formatting. This example highlights errors in red. ```javascript 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)) }); ``` -------------------------------- ### Implement Pre-Action Life Cycle Hook Source: https://github.com/tj/commander.js/blob/master/Readme.md Add a 'preAction' hook to execute logic before a command's action handler. This example logs trace information if the --trace option is enabled, showing arguments and options of the action command. ```javascript program .option('-t, --trace', 'display trace statements for commands') .hook('preAction', (thisCommand, actionCommand) => { if (thisCommand.opts().trace) { console.log(`About to call action handler for subcommand: ${actionCommand.name()}`); console.log('arguments: %O', actionCommand.args); console.log('options: %o', actionCommand.opts()); } }); ``` -------------------------------- ### Advanced Options Invalid Choice Example Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows the error message when an invalid choice is provided for an option configured with `.choices()`. ```console $ extra --drink huge error: option '-d, --drink ' argument 'huge' is invalid. Allowed choices are small, medium, large. ``` -------------------------------- ### Combined Short Options Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates combining multiple boolean short options and a single short option that takes a value. For example, '-d -s -p cheese' can be written as '-ds -p cheese' or '-dsp cheese'. ```console $ pizza-options -p error: option '-p, --pizza-type ' argument missing $ pizza-options -d -s -p vegetarian { debug: true, small: true, pizzaType: 'vegetarian' } pizza details: - small pizza size - vegetarian $ pizza-options --pizza-type=cheese pizza details: - cheese ``` -------------------------------- ### Configuring Help Command (Current Usage) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Shows the current methods for configuring the help command using `.helpCommand()` or `.addHelpCommand()` with a Command object. ```javascript program.helpCommand('assist [command]'); program.helpCommand('assist', 'show assistance'); program.helpCommand(false); program.addHelpCommand(new Command('assist').argument('[command]').description('show assistance')); ``` -------------------------------- ### Advanced Options with Environment and Preset Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates how environment variables and presets are applied, along with implied options, when parsing command-line arguments. ```console $ PORT=80 extra --donate --free-drink Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' } ``` -------------------------------- ### Create Command Instance Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates creating a new command instance using the exported createCommand factory function. ```javascript import { createCommand } from 'commander'; const program = createCommand(); ``` -------------------------------- ### Configuring Help Command (Deprecated Usage) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Demonstrates deprecated ways of using `addHelpCommand` with string or boolean parameters. ```javascript program.addHelpCommand('assist [command]'); program.addHelpCommand('assist', 'show assistance'); program.addHelpCommand(false); ``` -------------------------------- ### Define options with varying argument counts Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Demonstrates how to define options that accept zero, one, or multiple arguments using bracket and ellipsis syntax. ```js program .option('-c, --compress [percentage]') // 0 or 1 .option('--preprocess ') // 1 or more .option('--test [name...]') // 0 or more ``` -------------------------------- ### Option Class Initialization Source: https://github.com/tj/commander.js/wiki/Class:-Option Initialize a new Option instance with flags and an optional description. ```APIDOC ## new Option(flags[, description]) ### Description Initialize a new `Option` with the given `flags` and `description`. ### Parameters - **flags** (string) - Required - The flags that can be used when calling the command. - **description** (string) - Optional - The description that is used in the automated help page. ``` -------------------------------- ### Version Option Console Output Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates the output when the default version option is used on the command line. ```console $ ./examples/pizza -V 0.0.1 ``` -------------------------------- ### Parse Command-Line Arguments Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates how to parse process.argv or a custom array of arguments. Use .parseAsync() for async action handlers. ```javascript program.parse(); // parse process.argv and auto-detect electron and special node flags program.parse(process.argv); // assume argv[0] is app and argv[1] is script program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0] ``` -------------------------------- ### Advanced Options Help Output Source: https://github.com/tj/commander.js/blob/master/Readme.md Displays the help message generated for the advanced options, showing available options, descriptions, defaults, and choices. ```console $ extra --help Usage: help [options] Options: -t, --timeout timeout in seconds (default: one minute) -d, --drink drink cup size (choices: "small", "medium", "large") -p, --port port number (env: PORT) --donate [amount] optional donation in dollars (preset: "20") --disable-server disables the server --free-drink small drink included free -h, --help display help for command ``` -------------------------------- ### Creating a Local Command Object (CommonJS) Source: https://github.com/tj/commander.js/blob/master/Readme.md Demonstrates how to create a local 'Command' object using require for CommonJS modules, recommended for larger programs and testing. ```javascript // CommonJS (.cjs) const { Command } = require('commander'); const program = new Command(); ``` -------------------------------- ### Default Import (Current) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md In newer versions, you can import `program` directly or import the `Command` object to instantiate. ```javascript const { program } = require('commander'); // or const { Command } = require('commander'); const program = new Command() ``` -------------------------------- ### Configure Help Command Source: https://github.com/tj/commander.js/blob/master/Readme.md Explicitly enable or disable the default help command, or customize its name and description. This command is automatically added if subcommands exist. ```javascript program.helpCommand('assist [command]', 'show assistance'); ``` -------------------------------- ### Option Configuration Methods Source: https://github.com/tj/commander.js/wiki/Class:-Option Methods for configuring the behavior and properties of an Option instance. ```APIDOC ## Option Methods ### argParser(fn) Set the custom handler for processing CLI option arguments into option values. - **fn** (function) - Optional ### attributeName() Return option name, in a camelcase format that can be used as a object attribute key. - **Returns** (string) - The name of the option in camelcase format ### choices(values) Only allow option value to be one of choices. - **values** (Array[string]) - Required - Array of choices allowed ### default(value[, description]) Set the default value, and optionally supply the description to be displayed in the help. - **value** (any) - Required - The default value - **description** (string) - Optional - The description that is shown on the help page ### env(name) Set the environment variable that is used to check for an option value. - **name** (string) - Required ``` -------------------------------- ### Deprecated Callback for .help() and .outputHelp() Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Using a callback with .help() and .outputHelp() to process help text before display is deprecated. Use .helpInformation() to access help text directly. ```javascript program.outputHelp((text) => { return colors.red(text); }); ``` ```javascript console.error(colors.red(program.helpInformation())); ``` -------------------------------- ### Creating a Local Command Object (TypeScript) Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows how to instantiate a local 'Command' object in TypeScript, using import for type safety and modern development practices. ```typescript // TypeScript (.ts) import { Command } from 'commander'; const program = new Command(); ``` -------------------------------- ### Creating a Local Command Object (ECMAScript) Source: https://github.com/tj/commander.js/blob/master/Readme.md Illustrates creating a local 'Command' object using import for ECMAScript modules (.mjs), suitable for modern JavaScript projects. ```javascript // ECMAScript (.mjs) import { Command } from 'commander'; const program = new Command(); ``` -------------------------------- ### Help Output Layout Diagram Source: https://github.com/tj/commander.js/blob/master/docs/help-in-depth.md Visual representation of the help output structure and the corresponding stringify/style routines used for each section. ```text Usage: color-help [options] [command] <-1--> <-------------2--------------> <---a----> <---b---> <---c---> program description <--------3--------> Options: <--1---> -h, --help display help for command <---4----> <---------5------------> Commands: <---1---> print [options] print files <----------6----------> <----7----> <-b-> <---c---> <--d--> ``` ```text Usage: color-help print [options] <-1--> <---------------2-------------------> <---a----> <-c-> <---b---> <---d----> Arguments: <---1----> files files to queue for printing <-8-> <------------9------------> ... ``` -------------------------------- ### Deprecated cmd.description() with Argument Descriptions Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md The cmd.description(cmdDescription, argDescriptions) syntax for adding command argument descriptions is deprecated. Use the .argument() method instead. ```javascript program .command('price ') .description('show price of book', { book: 'ISBN number for book' }); ``` ```javascript program .command('price') .description('show price of book') .argument('', 'ISBN number for book'); ``` -------------------------------- ### Subcommand with Descriptions and Options Source: https://github.com/tj/commander.js/blob/master/Readme.md Defines a CLI tool with a 'split' subcommand that splits a string using a specified separator and optionally displays only the first result. Includes descriptions for the command, arguments, and options. ```javascript import { Command } from 'commander'; const program = new Command(); program .name('string-util') .description('CLI to some JavaScript string utilities') .version('0.8.0'); program.command('split') .description('Split a string into substrings and display as an array') .argument('', 'string to split') .option('--first', 'display just the first substring') .option('-s, --separator ', 'separator character', ',') .action((str, options) => { const limit = options.first ? 1 : undefined; console.log(str.split(options.separator, limit)); }); program.parse(); ``` ```console $ node string-util.js help split Usage: string-util split [options] Split a string into substrings and display as an array. Arguments: string string to split Options: --first display just the first substring -s, --separator separator character (default: ",") -h, --help display help for command $ node string-util.js split --separator=- a-b-c [ 'a', 'b', 'c' ] ``` -------------------------------- ### Set Command Summary and Description Source: https://github.com/tj/commander.js/blob/master/Readme.md Define a shorter summary for use when the command is listed as a subcommand, and a more detailed description for the command's own help output. This improves clarity for users navigating subcommands. ```javascript program .command("duplicate") .summary("make a copy") .description("Make a copy of the current project.\nThis may require additional disk space. "); ``` -------------------------------- ### Deprecated .on('--help') Event Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md The .on('--help') event was used to add custom help text after the built-in help. It is replaced by the .addHelpText() method. ```javascript program.on('--help', function() { console.log('') console.log('Examples:'); console.log(' $ custom-help --help'); console.log(' $ custom-help -h'); }); ``` ```javascript program.addHelpText('after', ` Examples: $ custom-help --help $ custom-help -h` ); ``` -------------------------------- ### Customize Usage Description Source: https://github.com/tj/commander.js/blob/master/Readme.md Customize the usage description that appears in the first line of the help output. This allows you to define how the command's usage should be presented to the user. ```javascript program .name("my-command") .usage("[global options] command"); ``` -------------------------------- ### Advanced Option Configuration Source: https://github.com/tj/commander.js/blob/master/Readme.md Illustrates configuring various advanced options using the `Option` class, including hidden options, defaults, choices, environment variables, presets, parsers, conflicts, and implications. ```javascript program .addOption(new Option('-s, --secret').hideHelp()) .addOption(new Option('-t, --timeout ', 'timeout in seconds').default(60, 'one minute')) .addOption(new Option('-d, --drink ', 'drink size').choices(['small', 'medium', 'large'])) .addOption(new Option('-p, --port ', 'port number').env('PORT')) .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)) .addOption(new Option('--disable-server', 'disables the server').conflicts('port')) .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' })); ``` -------------------------------- ### Importing Commander Program Object Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows the import statement for using the global 'program' object from Commander.js, suitable for quick scripts. ```javascript import { program } from 'commander'; ``` -------------------------------- ### Listen to Option Events Source: https://github.com/tj/commander.js/blob/master/Readme.md Execute custom actions by listening to specific option events. This allows you to perform logic based on user-provided options, such as setting environment variables. ```javascript program.on('option:verbose', function () { process.env.VERBOSE = this.opts().verbose; }); ``` -------------------------------- ### Action Handler with Options and Command Object Source: https://github.com/tj/commander.js/blob/master/Readme.md The action handler receives parameters for each declared command-argument, plus parsed options and the command object itself. ```javascript program .argument('') .option('-t, --title ', '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}`); }); ``` -------------------------------- ### Deprecated .command('*') for Default Command Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Using .command('*') to define a default command is deprecated. Use the 'isDefault: true' configuration option when adding a command. ```javascript program .command('*') .action(() => console.log('List files by default...')); ``` ```javascript program .command('list', { isDefault: true }) .action(() => console.log('List files by default...')); ``` -------------------------------- ### Define Required and Optional Arguments with Descriptions Source: https://github.com/tj/commander.js/blob/master/Readme.md Use `.argument()` to specify command-line arguments with their names and descriptions. Arguments can be required () or optional ([name]), with optional arguments supporting default values. ```javascript program .version('0.1.0') .argument('', 'user to login') .argument('[password]', 'password for user, if required', 'no password given') .action((username, password) => { console.log('username:', username); console.log('password:', password); }); ``` -------------------------------- ### Style Help Output Source: https://github.com/tj/commander.js/blob/master/docs/help-in-depth.md Applies custom styling to help text elements, such as making titles bold using node:util's styleText. ```js import { styleText } from 'node:util'; program.configureHelp({ styleTitle: (str) => styleText('bold', str) }); ``` -------------------------------- ### Add Multiple Arguments at Once Source: https://github.com/tj/commander.js/blob/master/Readme.md Use `.arguments()` to add multiple arguments simultaneously without descriptions. ```javascript program .arguments(' '); ``` -------------------------------- ### Configure Help Behavior Source: https://github.com/tj/commander.js/blob/master/docs/help-in-depth.md Modifies help output settings such as sorting subcommands and customizing the subcommand term display. ```js program.configureHelp({ sortSubcommands: true, subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage. }); ``` ```js program.configureHelp({ subcommandTerm: (cmd) => cmd.name() // just show the name instead of usage }); ``` -------------------------------- ### Define Commands with Action Handlers Source: https://github.com/tj/commander.js/blob/master/Readme.md Defines a 'clone' subcommand using an action handler. This approach attaches the command's logic directly to the command definition. ```javascript // Command implemented using action handler (description is supplied separately to `.command`) // Returns new command for configuring. program .command('clone [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, indicated by adding description as second parameter to `.command`. // Returns `this` for adding more commands. program .command('start ', '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()); ``` -------------------------------- ### Show Help After Errors Source: https://github.com/tj/commander.js/blob/master/Readme.md Configure Commander.js to display the full help message or a custom message after an error occurs. This is useful for providing more context to the user when they make a mistake. ```javascript program.showHelpAfterError(); // or program.showHelpAfterError('(add --help for additional information)'); ``` -------------------------------- ### Set Program Name Source: https://github.com/tj/commander.js/blob/master/Readme.md Specify the program name, which appears in the help output and is used for locating subcommands. The name can be set using `.name()` or in the `Command` constructor. ```javascript program.name('pizza'); const pm = new Command('pm'); ``` -------------------------------- ### Handle parsing ambiguity with command arguments Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Shows a scenario where an option argument might be incorrectly consumed as a command argument, and how to use '--' to resolve it. ```js program .name('cook') .argument('[technique]') .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient') .action((technique, options) => { console.log(`technique: ${technique}`); const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient; console.log(`ingredient: ${ingredient}`); }); program.parse(); ``` ```sh $ cook scrambled technique: scrambled ingredient: undefined $ cook -i technique: undefined ingredient: cheese $ cook -i egg technique: undefined ingredient: egg $ cook -i scrambled # oops technique: undefined ingredient: scrambled ``` ```sh $ node cook.js -i -- scrambled technique: scrambled ingredient: cheese ``` -------------------------------- ### Define Boolean and Value Options Source: https://github.com/tj/commander.js/blob/master/Readme.md Defines boolean options (e.g., --debug) and options that take a value from the next argument (e.g., --expect ). Options are undefined unless specified on the command line. ```javascript program .option('-d, --debug', 'output extra debugging') .option('-s, --small', 'small pizza size') .option('-p, --pizza-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}`); ``` -------------------------------- ### Store Options as Properties Source: https://github.com/tj/commander.js/blob/master/Readme.md Reverts to legacy behavior where option values are stored as properties on the command object. Useful for unmodified legacy code. ```javascript program .storeOptionsAsProperties() .option('-d, --debug') .action((commandAndOptions) => { if (commandAndOptions.debug) { console.error(`Called ${commandAndOptions.name()}`); } }); ``` -------------------------------- ### Resolve ambiguity by ordering options last Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Updates the usage pattern to place options after command arguments, ensuring clear separation. ```js program.usage('[technique] [options]'); ``` ```sh $ cook --help Usage: cook [technique] [options] Options: -i, --ingredient [ingredient] add cheese or given ingredient -h, --help display help for command $ node cook.js scrambled -i technique: scrambled ingredient: cheese ``` -------------------------------- ### ESM Import (Current) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Named imports can now be imported directly from the main module. ```javascript import { Command } from 'commander'; ``` -------------------------------- ### Running TypeScript Executables with ts-node Source: https://github.com/tj/commander.js/blob/master/Readme.md Shows how to execute TypeScript files as standalone executables using ts-node. Requires calling the program through node. ```bash node -r ts-node/register pm.ts ``` -------------------------------- ### Display Automated Help Information Source: https://github.com/tj/commander.js/blob/master/Readme.md Commander automatically generates help messages based on program configuration. The default help option is -h,--help. A 'help' command is added by default for programs with subcommands. ```console $ node ./examples/pizza --help Usage: pizza [options] An application for pizza ordering Options: -p, --peppers Add peppers -c, --cheese Add the specified type of cheese (default: "marble") -C, --no-cheese You do not want any cheese -h, --help display help for command ``` -------------------------------- ### Change Default Help Option Source: https://github.com/tj/commander.js/blob/master/Readme.md Modify the default help flags and description for the built-in help option. You can also disable the help option entirely by passing `false`. ```javascript program .helpOption('-e, --HELP', 'read more information'); ``` -------------------------------- ### Define Stand-alone Subcommands Source: https://github.com/tj/commander.js/blob/master/Readme.md Configure Commander to use separate executable files for subcommands. Commander searches for files named like 'command-subcommand' in the entry script's directory. Options for subcommands are handled within their respective executables. ```javascript program .name('pm') .version('0.1.0') .command('install [package-names...]', '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); ``` -------------------------------- ### Basic Option and Argument Parsing Source: https://github.com/tj/commander.js/blob/master/Readme.md Parses command-line arguments with a required string argument and optional flags for a separator and a first element. Displays an error for unrecognized options. ```javascript import { program } from 'commander'; program .option('--first') .option('-s, --separator ') .argument(''); program.parse(); const options = program.opts(); const limit = options.first ? 1 : undefined; console.log(program.args[0].split(options.separator, limit)); ``` ```console $ node split.js -s - --fits a-b-c error: unknown option '--fits' (Did you mean --first?) $ node split.js -s - --first a-b-c [ 'a' ] ``` -------------------------------- ### Add Arguments with Choices and Defaults Source: https://github.com/tj/commander.js/blob/master/Readme.md Construct `Argument` objects explicitly to define arguments with choices or custom default values. ```javascript program .addArgument(new commander.Argument('', 'drink cup size').choices(['small', 'medium', 'large'])) .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute')) ``` -------------------------------- ### TypeScript Import for Extra Typings Source: https://github.com/tj/commander.js/blob/master/Readme.md Imports the Command type from the optional commander-js/extra-typings project for strong typing. ```typescript import { Command } from '@commander-js/extra-typings'; ``` -------------------------------- ### ESM Import (Deprecated) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Previously, named imports required an explicit entry file like `commander/esm.mjs`. ```javascript import { Command } from 'commander/esm.mjs'; ``` -------------------------------- ### Replace command arguments with options Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Eliminates parsing ambiguity entirely by converting positional command arguments into named options. ```js program .name('cook') .option('-t, --technique ', 'cooking technique') .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient') .action((options) => { console.log(`technique: ${options.technique}`); const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient; console.log(`ingredient: ${ingredient}`); }); ``` ```sh $ cook -i -t scrambled technique: scrambled ingredient: cheese ``` -------------------------------- ### Accessing Registered Arguments (Current) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md The registered command arguments are now accessible via the `.registeredArguments` property. ```javascript const registeredArguments = program.registeredArguments; ``` -------------------------------- ### Accessing Registered Arguments (Deprecated) Source: https://github.com/tj/commander.js/blob/master/docs/deprecated.md Previously, command arguments were accessed via the private `_args` property. This method is deprecated. ```javascript const registeredArguments = program._args; ``` -------------------------------- ### Configure Option Parsing Behavior Source: https://github.com/tj/commander.js/blob/master/docs/options-in-depth.md Modify Commander.js's behavior for parsing options that take optional values. Set to `false` to treat combined short options as separate booleans, mimicking pre-v5 behavior. ```javascript .combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour .combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l` ``` -------------------------------- ### Set Default Option Value Source: https://github.com/tj/commander.js/blob/master/Readme.md Specifies a default value for an option. If the option is not provided on the command line, its default value is used. ```javascript program .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); program.parse(); console.log(`cheese: ${program.opts().cheese}`); ``` -------------------------------- ### Define Required Option Source: https://github.com/tj/commander.js/blob/master/Readme.md Specifies a mandatory option using `.requiredOption()`. This option must be provided on the command line or have a default value (e.g., from environment) to avoid an error. ```javascript program .requiredOption('-c, --cheese ', 'pizza must have cheese'); program.parse(); ``` -------------------------------- ### Action Handler Using 'this' Context Source: https://github.com/tj/commander.js/blob/master/Readme.md When using a function expression (not an arrow function) for the action handler, 'this' is bound to the running command, allowing access to arguments and options via `this.args` and `this.opts()`. ```javascript program .command('serve') .argument('