Architecture
Relevant source files
* lib/command.js * lib/option.js * lib/help.js * examples/split.js * examples/string-util.js * examples/configure-output.js * tests/imports.test.cjs * tests/argument.required.test.js * tests/help.commandUsage.test.js * tests/command.description.test.jsCommander.js Architecture
Overview
Commander.js is a Node.js package for building command-line interfaces (CLI). It provides a simple and intuitive API for defining commands, options, and arguments. In this documentation, we will explore the internal workings of Commander.js and how it handles commands and options.
Commands
A command is a top-level entity in Commander.js that represents a specific action or task. Commands can have subcommands, options, and arguments. The Command class is the base class for all commands.
Options
Options are used to customize the behavior of a command. They can be defined using the .option() method, which takes a string argument that specifies the option's name and description. Options can be boolean, value, or negatable boolean.
Arguments
Arguments are used to pass data to a command. They can be defined using the .argument() method, which takes a string argument that specifies the argument's name and description. Arguments can be required or optional.
Help
Commander.js provides a built-in help system that can be used to display information about a command or its options and arguments. The Help class is responsible for generating the help output.
Parsing
Commander.js uses a parser to parse the command-line arguments and options. The parser is responsible for validating the input and generating an error message if the input is invalid.
Configuration
Commander.js provides a configuration system that allows you to customize its behavior. You can configure the parser, the help system, and other aspects of Commander.js.
Example
Here is an example of how to use Commander.js to define a command:
const { Command } = require('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>', 'string to split')
.option('--first', 'display just the first substring')
.option('-s, --separator <char>', 'separator character', ',')
.action((str, options) => {
const limit = options.first ? 1 : undefined;
console.log(str.split(options.separator, limit));
});
program.parse();
This code defines a command named string-util with a subcommand named split. The split command takes a string argument and has two options: --first and -s, --separator <char>.
Mermaid Diagram
graph TD
A[Command] --> B[Subcommand]
B --> C[Option]
C --> D[Argument]
D --> E[Action]
E --> F[Help]
F --> G[Parser]
G --> H[Configuration]
This diagram shows the relationships between the different components of Commander.js.