Command Line Subcommands in JavaScript

Our first program will demonstrate how to create command-line subcommands in JavaScript. Here’s the full source code:

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

// Define the foo subcommand
program
  .command('foo')
  .option('-e, --enable', 'enable')
  .option('-n, --name <name>', 'name')
  .action((options, command) => {
    console.log("subcommand 'foo'");
    console.log("  enable:", options.enable || false);
    console.log("  name:", options.name || '');
    console.log("  tail:", command.args);
  });

// Define the bar subcommand
program
  .command('bar')
  .option('-l, --level <level>', 'level', parseInt)
  .action((options, command) => {
    console.log("subcommand 'bar'");
    console.log("  level:", options.level || 0);
    console.log("  tail:", command.args);
  });

// Parse the command-line arguments
program.parse(process.argv);

// If no subcommand is provided, show an error message
if (!process.argv.slice(2).length) {
  console.log("expected 'foo' or 'bar' subcommands");
  process.exit(1);
}

To run the program, save it as command-line-subcommands.js and use node:

First, install the required dependency:

$ npm install commander

Now you can run the program:

$ node command-line-subcommands.js foo --enable --name=joe a1 a2
subcommand 'foo'
  enable: true
  name: joe
  tail: [ 'a1', 'a2' ]

$ node command-line-subcommands.js bar --level 8 a1
subcommand 'bar'
  level: 8
  tail: [ 'a1' ]

Note that the bar subcommand won’t accept foo’s flags:

$ node command-line-subcommands.js bar --enable a1
error: unknown option '--enable'

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.