The ubiquitous CLI tools,

For example vue – the cli:

Parsing parameters using the COMMANDER module is especially important if you want to understand what the tool does.

Principle:

When a Nodejs program runs, the Process object has a property called argv. The first big part of the command line program is parsing the process.argv property.

Define a Hello script that prints process.argv

#! /usr/bin/env node
console.log('hello ', process.argv);Copy the code
Type $hello a b c at the terminal

Argv looks like an array, where the first element is node’s execution path, the second element is the path to the current execution file, and starting with the third element, the arguments that are carried in at execution time.

You can of course parse the argv arguments yourself

Using the commander. Js

Commander. Js is a toolkit written by TJ that makes node command line programming much easier.

Installation and use

Installation is simple,

$ npm install commanderCopy the code

// file: ./bisheng
#! /usr/bin/env node
const program = require('commander');
const package = require('.. /package.json');
program
  .version(package.version)
  .option('-f, --foo'.'enable some foo')  
  .option('-b, --bar'.'enable some bar')  
  .option('-B, --baz'.'enable some baz');

  program.on('--help'.function(){  
   console.log(' ');  
   console.log('Examples:');  
   console.log(' $ custom-help --help');
   console.log(' $ custom-help -h');
  });

  program.parse(process.argv);Copy the code

Command to execute it $./bisheng -hCopy the code



The first advantage of commander.js is that it provides an introductory API for parsing options and arguments. The second advantage is automatically generating help text messages.

Commonly used API

  • version

Example:.version(‘0.0.1’, ‘-v, –version’) parameter resolution:


  1. First argument version number < must >
  2. The second parameter custom flag < omitted > : defaults to -v and –version

When we type./bisheng -v or./bisheng –version we can output the corresponding version number

  • option

Function: used to define the command options: option (‘ – n – name < name > ‘, ‘your name’ and ‘GK)

  1. The first parameter custom flag < must > : divided into long and short marks, separated by commas, vertical lines or Spaces; .
    1. Flags can be followed by parameters, which can be modified with <> or [], with the former meaning required and the latter meaning optional
  2. The second parameter option description < omit without error > : display flag description when using the –help command
  3. Third parameter Parameter Default value, optional.

Execute command $./bisheng –name 123

The value of program.name is 123. If 123 is not entered, the default value GK is usedCopy the code
  • command

Usage Example:.command(‘rmdir [otherDirs… ‘, ‘install description’, opts)

Parameter analysis:

  1. First argument Command name < must > : the command can be followed by arguments contained in <> or []. The last argument to the command can be variable, adding otherDirs after the array as in the example. Mark; Arguments passed after the command are passed to the action callback and to the program.args array
  2. The second argument command description < omitted > : if it exists and no action(fn) is displayed, the subcommand program is started, otherwise an error is reported
      • Commander.js returns when there is no second argumentCommandObject, with a second argument, returns the prototype object.
      • When a second argument is taken and no call is displayedaction(fn), the subcommand mode will be used.
      • The subcommand mode is,./pm../pm-install../pm-searchAnd so on. These subcommands are in separate files from the main command.

3. Configuration option < optional > : noHelp and isDefault can be configured



  • alias

Use: custom alias usage. Alias (‘ex’)


  • description

Usage Example:.description(‘rmdir desc’)


  • action

Usage: the action (fn)

Used to set the related callbacks for command execution. Fn can accept commands as function parameters in the same order as defined in command().


parse

Usage: the program. The parse (process. Argv)

This API is typically called last and is used to parse process.argv.


outputHelp

Usage: program. OutputHelp ()

Generally, the help information is automatically printed when no parameter is entered


Argument parsing

The.option() method is used to define commanders with options, as well as to document those options. The following example parses the parameters and options specified by process.argv. Parameters that do not match any of the options will be placed in the program.args array.

#! /usr/bin/env node

var program = require('commander');

program
  .version('0.0.1')
  .option('-p, --peppers'.'Add peppers')
  .option('-P, --pineapple'.'Add pineapple')
  .option('-b, --bbq-sauce'.'Add bbq sauce')
  .option('-c, --cheese [type]'.'Add the specified type of cheese [marble]'.'marble')
  .parse(process.argv);

console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);Copy the code

$./bisheng -p or./bisheng — Peppers

A value of the program. The pepperstrueCopy the code



Execute command $./bisheng -c 123

The value of program.cheese is 123. The default value is marbleCopy the code




Add handler function

#! /usr/bin/env node
var program = require('commander');


function range(val) {
  return val.split('.. ').map(Number);
}

function list(val) {
  return val.split(', ');
}

function collect(val, memo) {
  memo.push(val);
  return memo;
}

function increaseVerbosity(v, total) {
  return total + 1;
}

program
  .version('0.0.1')
  .usage('[options] 
        
          '
        )
  .option('-i, --integer <n>'.'An integer argument', parseInt)
  .option('-f, --float <n>'.'A float argument', parseFloat)
  .option('-r, --range .. '.'A range', range)
  .option('-l, --list <items>'.'A list', list)
  .option('-o, --optional [value]'.'An optional value')
  .option('-c, --collect [value]'.'A repeatable value', collect, [])
  .option('-v, --verbose'.'A value that can be increased', increaseVerbosity, 0)
  .parse(process.argv);

console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j.. %j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);Copy the code

The following information is displayed:



Regular expression

program
  .version('0.0.1')
  .option('-s --size <size>'.'Pizza size', /^(large|medium|small)$/i, 'medium')
  .option('-d --drink [drink]'.'Drink', /^(coke|pepsi|izze)$/i)
  .parse(process.argv);

console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);Copy the code

Variable parameter

The last argument to a command can be mutable, and only the last argument can be mutable. To make the argument variable, you need to append… . Here’s an example:

#! /usr/bin/env node

var program = require('commander');

program
  .version('0.0.1')
  .command('rmdir 
        
          [otherDirs...] '
        )
  .action(function (dir, otherDirs) {
    console.log('rmdir %s', dir);
    if (otherDirs) {
      otherDirs.forEach(function (oDir) {
        console.log('rmdir %s', oDir); }); }}); program.parse(process.argv);Copy the code

Execute $./ Bisheng RMdir dir May Day holiday home

rmdir <dir> [otherDirs...] Dir takes the argument dir otherDirs as an array takes all the following arguments (variable arguments)Copy the code



Syntax for specifying parameters

Angle brackets (such as < CMD >) represent required input and square brackets (such as [env]) represent optional input.

#! /usr/bin/env node

var program = require('commander');

program
  .version('0.0.1')
  .arguments('<cmd> [env]')
  .action(function (cmd, env) {
     cmdValue = cmd;
     envValue = env;
  });

program.parse(process.argv);

if (typeof cmdValue === 'undefined') {
   console.error('no command given! ');
   process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");Copy the code



Git style subcommands

// file: ./bin/bisheng
#! /usr/bin/env node
const program = require('commander');
const package = require('.. /package.json');
program  .version(package.version)
  .usage('[command] [options]')
  .command('start [options]'.'to start a server')
  .command('build [options]'.'to build and write static files to `config.output`')
  .command('gh-pages [options]'.'to deploy website to gh-pages',{isDefault: true})
  .parse(process.argv);Copy the code

When.command() has a description argument, you cannot use.action(callback) to process subcommands, otherwise an error will occur. This tells Commander that you will use a separate executable as a subcommand. Commander will try to search the directory of the entry script (e.g./bin/bisheng) for program-command executable files such as bisheng-start, bisheng-build,bisheng-gh-pages.

As follows:



You can pass options when calling.command(). Specifying opts.nohelp to true strips this option from the generated help output. Specifying opts. IsDefault to true will execute the subcommand if no other subcommand is specified.

Automated help message –help

The commander help information is automatically generated based on your application, as shown below--helpGenerated help information:


Custom Help

You can control -h by listening on –help, and –help displays any information. Once the call is complete, Commander will exit automatically and the rest of your program will not be shown. For example, “stuff” below will not be printed when –help is executed.

#! /usr/bin/env node
var program = require('commander');

program
  .version('0.0.1')
  .option('-f, --foo'.'enable some foo')
  .option('-b, --bar'.'enable some bar')
  .option('-B, --baz'.'enable some baz');

program.on('--help'.function(){
  console.log(' ');
  console.log('Examples:');
  console.log(' $ custom-help --help');
  console.log(' $ custom-help -h');
});

program.parse(process.argv);

console.log('stuff');
Copy the code


.outputHelp(cb)

Do not exit the output help information. Optional callbacks can be processed after the help text is displayed. If you want to display the default help (for example, if no command is provided), you can use something like this:

var program = require('commander');
var colors = require('colors');

program
  .version('0.0.1')
  .command('getstream [url]'.'get stream URL')
  .parse(process.argv);

  if(! process.argv.slice(2).length) { program.outputHelp(make_red); }function make_red(txt) {
  returncolors.red(txt); // Display red help text on the console}Copy the code