Commander writes his Nodejs command

Posted by Amgine on Wed, 10 Jul 2019 01:17:48 +0200

1. Introduction to Commander

Commander is a lightweight nodejs module, which provides powerful functions of user command line input and parameter parsing. The commander comes from a Ruby project of the same name.

The characteristics of commander:

  • Self-recording code
  • Automatic Generation Help
  • Merge short parameters ("ABC"=="-A-B-C")
  • Default options
  • Mandatory Options
  • Command parsing
  • Prompt

2. commander Installation

npm install commander

Write a simple example: add the file app.js

~ vi app.js

var program = require('commander');
program
    .version('0.0.1')
    .option('-p, --peppers', 'Add peppers')
    .option('-P, --pineapple', 'Add pineapple')
    .option('-b, --bbq', '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.bbq) console.log('  - bbq');
console.log('  - %s cheese', program.cheese);

Command line input test:

//No parameters
~ D:\workspace\javascript\nodejs-commander>node app.js
you ordered a pizza with:
  - marble cheese

//A parameter
~ D:\workspace\javascript\nodejs-commander>node app.js -c
you ordered a pizza with:
  - marble cheese

//Multiple parameters
~ D:\workspace\javascript\nodejs-commander>node app.js -cbp
you ordered a pizza with:
  - peppers
  - bbq
  - marble cheese

//help
~ D:\workspace\javascript\nodejs-commander>node app.js --help

  Usage: app.js [options]
  Options:
    -h, --help           output usage information
    -V, --version        output the version number
    -p, --peppers        Add peppers
    -P, --pineapple      Add pineapple
    -b, --bbq            Add bbq sauce
    -c, --cheese [type]  Add the specified type of cheese [marble]
//Version
~ D:\workspace\javascript\nodejs-commander>node app.js -V

0.0.1

3. API of commander

  • Option(): Initialize custom parameter objects, set keywords and descriptions
  • Command(): Initialize the command line parameter object and get the command line input directly
  • Command#command(): Define a command name
  • Command action (): Register a callback function
  • Command option (): To define parameters, you need to set up "keywords" and "descriptions". Keywords include "abbreviation" and "full writing", separated by ",""|" and "blank".
  • Command parse (): parse the command line parameter argv
  • Command description (): Set the description value
  • Command usage (): Set the usage value
    Refer to the official API example.

4. Develop custom commands

Requirement description: Design a server startup command, including self-command: specify deployment node, configuration selection: deployment directory, deployment configuration file, allowable IP list, start seed value, calculated threshold interval.

New file: myServer.js

~ vi myServer.js

var program = require('commander');

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

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

program
.version('0.0.1')
.usage('test')
.option('-C, --chdir [value]', 'Setting up server nodes','/home/conan/server')
.option('-c, --config [value]', 'Setting up configuration files','./deploy.conf')
.option('-m, --max <n>', 'maximum connection', parseInt)
.option('-s, --seed <n>', 'Initial seed', parseFloat)
.option('-r, --range <a>..<b>', 'Threshold interval', range)
.option('-l, --list <items>', 'IP list', list)

program
.command('deploy <name>')
.description('Deploy a service node')
.action(function(name){
console.log('Deploying "%s"', name);
});

program.parse(process.argv);

console.log(' chdir - %s ', program.chdir);
console.log(' config - %s ', program.config);
console.log(' max: %j', program.max);
console.log(' seed: %j', program.seed);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
//View Help Information

~ D:\workspace\javascript\nodejs-commander>node myServer.js -h

Usage: myServer.js test

Commands:

deploy <name> Deploy a service node

Options:

-h, --help output usage information
-V, --version output the version number
-C, --chdir [value] Setting up server nodes
-c, --config [value] Setting up configuration files
-m, --max <n> maximum connection
-s, --seed <n> Initial seed
-r, --range <a>..<b> Threshold interval
-l, --list <items> IP list

//Start from the command line:

~ D:\workspace\javascript\nodejs-commander>node myServer.js -c /deploy/c1/config.conf -m 20 -s 19.1 -r 12..101 -l 192.168.1.1,192.168.1.2,192.168.1.3 deploy server1

Deploying "server1"
 chdir - /home/conan/server
 config - /deploy/c1/config.conf
 max: 20
 seed: 19.1
 range: 12..101
 list: ["192.168.1.1","192.168.1.2","192.168.1.3"]

5. Publish as Running Command

In fact, simply rewrite myServer.js. Define startup scripts:

#!/usr/bin/env node

New command file bin/myServer

~ D:\workspace\javascript\nodejs-commander>mkdir bin
~ vi myServer

#!/usr/bin/env node

var program = require('commander');

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

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

program
    .version('0.0.1')
    .usage('test')
    .option('-C, --chdir [value]', 'Setting up server nodes','/home/conan/server')
    .option('-c, --config [value]', 'Setting up configuration files','./deploy.conf')
    .option('-m, --max ', 'maximum connection', parseInt)
    .option('-s, --seed ', 'Initial seed', parseFloat)
    .option('-r,--range <a>..<b>', 'Threshold interval', range)
    .option('-l, --list ', 'IP list', list)

program
    .command('deploy ')
    .description('Deploy a service node')
    .action(function(name){
        console.log('Deploying "%s"', name);
    });

program.parse(process.argv);

console.log(' chdir - %s ', program.chdir);
console.log(' config - %s ', program.config);
console.log(' max: %j', program.max);
console.log(' seed: %j', program.seed);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);

Running by command

~ D:\workspace\javascript\nodejs-commander>node bin\myServer -c /deploy/c1/config.conf -m 20 -s 19.1 -r 12..101 -l 192.168
.1.1,192.168.1.2,192.168.1.3 deploy server1

Deploying "server1"
 chdir - /home/conan/server
 config - /deploy/c1/config.conf
 max: 20
 seed: 19.1
 range: 12..101
 list: ["192.168.1.1","192.168.1.2","192.168.1.3"]

Original:
http://blog.fens.me/nodejs-commander/

Topics: Javascript Ruby npm