Make writing a habit together! This is the second day of my participation in the “Gold Digging Day New Plan · April More text challenge”. Click here for more details.

Commander usage

The installation

npm i -S commander
Copy the code

Creating a scaffold instance

// Get the commander scaffold singleton
const { program } = commander;

// Manually create a new Commander instance
const program = new commander.Command();
Copy the code

use

program
  .name(Object.keys(pkg.bin)[0]) // Set the usage name
  .usage('<command>[options]') // Set the usage message
  .parse(process.argv); // Parse the parameters
Copy the code

program
  .version(pkg.version) // Set the Version command
  .parse(process.argv); // Parse the parameters
Copy the code

program
  .option('-d, --debug'.'Debug mode enabled? '.true) // Create the debug command. The third parameter is whether this command is enabled by default
  .option('-e, --envName <envName>'.'Get environment variable name') // Create the envName command
  .parse(process.argv); // Parse the parameters
Copy the code

Other common apis

You can get parameters and default values

// Prints the options for the command
console.log(program.opts());
Copy the code

You can see that the help information is still printed without entering -h or –help

// Print the help information
program.outputHelp();
Copy the code

Register the command

Method 1: command Registers a command

const clone = program.command('clone <source> [destination]');
clone
  .description('Clone a warehouse')
  .option('-f, --force'.'Force clone or not') // Register option under clone command
  .action((source, destination, cmdObj) = > {
    console.log('do clone', source, destination, cmdObj);
  });
Copy the code

Method 2: addCommand Registers a command

// Create a new command
const service = new commander.Command('service').description('Start a service');

// Add a subcommand
service
  .command('start [port]')
  .description('Start service')
  .action((port) = > {
    console.log('service starts on${port}`);
  });

// Add a subcommand
service
  .command('stop')
  .description('Out of service')
  .action(() = > {
    console.log('Service stopped');
  });

// Add the command to the scaffold
program.addCommand(service);
Copy the code

Match all commands

// Match all nonexistent commands
program
  .arguments('<cmd> [option]')
  .description('Friendly reminder :', {
    cmd: 'There must be a command.'.option: 'There is an optional argument',
  })
  .action((cmd, option) = > {
    console.log(cmd, option);
  });
Copy the code

<> indicates mandatory, and [] indicates optional. There has to be a command.

-h will prompt you

Scaffolding calls each other

Spell install on the scaffold name to execute the new command, such as test-cli-install

// Execute a new command to call each other between scaffolds
program
  .command('install [name]'.'install package', {
    executableFile: 'hzw-cli-dev'.// Switch the name of the command to be executed
    isDefault: true.// This command is executed by default
    hidden: true.// Hide the command
  })
  .alias('i');
Copy the code

PS: I don’t know why this is not the same as the demo, BUT I implemented this to find the module, probably because of the version problem.

Advanced Customize help information

program.helpInformation = function () {
  return ' ';
};

program.on('--help'.function () {
  console.log('I'm a help message');
});
Copy the code

Executing -h again does not show up as before, but instead calls our custom method.

Advanced customization implements debug mode

Note: It is still not possible to print verbose before scaffold initialization after parsing parameters. You can use this method instead of wrapping your own code to enable debug mode.

program.on('option:debug'.() = > {
  console.log('Enable Debug mode');
  if (program._optionValues.debug) {
    process.env.LOG_LEVEL = 'verbose';
  }
  console.log(process.env.LOG_LEVEL);
});
Copy the code

Advanced customization listens for all unknown commands

When an unknown command is entered, a custom callback is executed.

program.on('command:*'.(obj) = > {
  const commands = program.commands.map((command) = > command.name());
  console.log('The command can be${commands.join(', ')}`);
});
Copy the code