Our first program will demonstrate how to create command-line subcommands in JavaScript. Here’s the full source code:
To run the program, save it as command-line-subcommands.js and use node:
First, install the required dependency:
Now you can run the program:
Note that the bar subcommand won’t accept foo’s flags:
This example demonstrates how to use the commander library in JavaScript to create subcommands with their own sets of flags. The program.command() method is used to define subcommands, and the option() method adds flags to each subcommand. The action() method defines what happens when a subcommand is invoked.
The structure is similar to the original example, but adapted to JavaScript’s syntax and the commander library’s API. Instead of using flag.NewFlagSet(), we use program.command() to create subcommands. The parsing of arguments is handled automatically by the commander library when we call program.parse(process.argv).
Next, we’ll look at environment variables, another common way to parameterize programs.