Two, yargs usage - yargs API

.command(cmd, desc, [builder], [handler])
.command(cmd, desc, [module])
.command(module)

 

Defined application command exposed
parameters: cmd, the command must be a string type name, or an array, the array type is string representing the name is an alias command or command
parameters: desc, it is used to describe the commands for What, if set desc is false, it will create a hidden command
optional parameters: builder, this command is used to prompt the parameters needs to receive

yargs 
  .command ( 'GET', 'the make the HTTP GET Request A' , { 
    URL: { 
      Alias: 'U' ,
       default : 'http://yargs.js.org/' 
    } 
  }) 
  .help () 
  .argv 

  may parameters selected from: builder, a method may be, the parameters of this method is yargs examples 
  yargs 
  .command ( 'GET', 'the make the HTTP GET Request a', function (yargs) {
     return yargs.option ( 'URL' , { 
      Alias: 'U' ,
       default : 'http://yargs.js.org/' 
    }) 
  }) 
  .help () 
  .argv 

//   you can also pass another processing function that will be called passing the treated argv
yargs
  .command(
    'get',
    'make a get HTTP request',
    function (yargs) {
      return yargs.option('u', {
        alias: 'url',
        describe: 'the URL to make an HTTP request to'
      })
    },
    function (argv) {
      console.log(argv.url)
    }
  )
  .help()
  .argv

.completion([cmd], [description], [fn]);

This is the command line for the full
participation of completion of the command cmd command definition. The first use will be prompted if using zsh, you will be prompted to change the .bashrc .zshrc, and follow the prompts (Remember to set your js file (chmod u + x) executable file, and irregular operation)
using the method described in the command description
fn provide a full complement of parameters to be

when implemented if not carrying parameters, then .completion () will complete the command output completion scripts

var argv = require('yargs')
  .completion('completion', function(current, argv) {
    // 'current' is the current command being completed.
    // 'argv' is the parsed arguments so far.
    // simply return an array of completions.
    return [
      'foo',
      'bar'
    ];
  })
  .argv;

  //还可以实现异步方法被全
  var argv = require('yargs')
  .completion('completion', function(current, argv, done) {
    setTimeout(function() {
      done([
        'Apple' ,
         'Banana' 
      ]); 
    }, 500 ); 
  }) 
  .argv;   // also return a completion object promise
  

 var the argv = the require ( 'yargs' ) 
  .completion ( 'Completion', function (Current , the argv) {
     return  new new Promise ( function (Resolve, Reject) { 
      the setTimeout ( function () { 
        Resolve ([ 'Apple', 'Banana' ]) 
      }, 10 ) 
    }) 
  }) 
  .argv;

.config ([key], [desction
], [parseFn]) This method is passed key, a path is equivalent JSON configuration file. JSON properties file is set to correspond to the key and value (hanging on argv). Nodejs file using the require api loaded, the file name is the best .js, .json.
If this method does not carry any parameters, .config () will use the --config option passing JSON configuration file (this time can only be passed to .json end of the file)
the Description with other methods, used to describe the command
options can parseFn used to customize the converter. Transfer function must be synchronized, and should be returned with a key, or the object to a key value error.

.config (object)
can also pass a definite object, the same, it's key to key argv will be converted into the right.
var argv = require ( "yargs"

config and pkgConf can offer extends keyword to indicate the configuration should inherit from elsewhere.
extends parameter can be either absolute or relative path

yargs.config({
  extends: "./configs/a.json",
  logLevel: "verbose"
}).argv;

// or may be a module (the function of which is useful, as Presets-Babel)
yargs.pkgConf ( 'NYC');

 

Custom package.json
{
"NYC": {
    "the extends": "Babel-NYC-config"
  }
}
NYC-config-Babel is a package, which is derived from the index configuration file

 

.conflicts (x, y);
After setting the x y can not be provided. y can be a string, or may be a group key does not coexist x

.count (key)
This command is used to command count, and converted to the parameters of the command, for example:

#!/usr/bin/env node
var argv = require("yargs")
  .count("verbose")
  .alias("v", "verbose").argv;

VERBOSE_LEVEL = argv.verbose;

function WARN() {
  VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments);
}
function INFO() {
  VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments);
}
function DEBUG() {
  VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments);
}

WARN("Showing only important stuff");
INFO("Showing semi-important stuff too");
DEBUG("Extra chatty mode");

.demandOption (key, [msg | boolean
]) .demandOption (key, msg) This command is used to force the user to input certain parameters
if the key is a string, and the key does not appear in the command line arguments, and exit display instructions .
If the key is an array, limiting parameters of each array
If a msg, but there is no corresponding parameter, msg will show, to replace the existing standard error message

require("yargs")
  .option("run", {
    alias: "r",
    describe: "run your program"
  })
  .option("path", {
    alias: "p",
    describe: "provide a path to file"
  })
  .option("spec", {
    alias: "s",
    describe: "program specifications"
  })
  .demandOption(
    ["run", "path"],
    "Please provide both run and path arguments to work with this tool"
  )
  .help().argv;

  // When the second parameter is a Boolean value, a Boolean value determines this option is not necessary. When using the method of options, this is useful 

the require ( "yargs" ) 
  .options ({ 
    RUN: { 
      Alias: "R & lt" , 
      DESCRIBE: "RUN your Program" , 
      demandOption: to true 
    }, 
    path: { 
      Alias: "P " , 
      DESCRIBE: " Provide A path to File " , 
      demandOption: to true 
    }, 
    spec: { 
      Alias: " S " , 
      DESCRIBE: " Program Specifications " 
    } 
  }) 
  .help ().

.demandCommand ([min = 1],
[minMsg]) .demandCommand ([min = 1], [max], [minMsg], [maxMsg]) This command is used to define the number of commands used in the user program. If the command is not passed in, using the standard error msg

require("yargs")
  .command({
    command: "configure <key> [value]",
    aliases: ["config", "cfg"],
    desc: "Set a config variable",
    builder: yargs => yargs.default("value", "true"),
    handler: argv => s
      console.log(`setting ${argv.key} to ${argv.value}`);
    }
  })
  // provide a minimum demand and a minimum demand message
  .demandCommand(1, "You need at least one command before moving on")
  .help().argv;

.hide (key)
to hide the information used in a key, unless --show-hidden with

var yargs = require("yargs")(['--help'])
  .showHidden('show-hidden', 'Show hidden options')
  .argv

.detectLocale (boolean)
yargs detect local operating system, the default is trues

.env ([prefix])
defined value of the environment variable, using the "_" to indicate nested option (nested__foo => nested.foo)

Program parameters define the priority order:

Command line parameters
env parameter
configuration file or object
default option

//fruity.js
var argv = require("yargs")
  .env("MY_PROGRAM")
  .option("f", {
    alias: "fruit-thing",
    default: "apple"
  }).argv;
console.log(argv);

$: node fruity.js
{ _: [],
  f: 'apple',
  'fruit-thing': 'apple',
  fruitThing: 'apple',
  '$0': 'fruity.js' }

  $ MY_PROGRAM_FRUIT_THING=banana node fruity.js
{ _: [],
  fruitThing: 'banana',
  f: 'banana',
  'fruit-thing': 'banana',
  '$0': 'fruity.js' }

  $ MY_PROGRAM_FRUIT_THING=banana node fruity.js -f cat
{ _: [],
  f: 'cat',
  'fruit-thing': 'cat',
  fruitThing: 'cat',
  '$0': 'fruity.js' }

.epilog (str)
.epilogue (str)
copy for use at the end of

var argv = require('yargs')
  .epilogue('for more information, find our manual at http://example.com');

.example (cmd, desc)
increases example, the first parameter cmd, the command line $ 0 for the first parameter. Examples will be printed with the help of information.

.exitProcess (enable)
if yargs .version result of the call or the verification fails or the command fails, the call exitProcess (false), to continue performing other normal instruction.

.exit (code, err)
initiative to withdraw from the program, and may prompt the context indicate why we want to quit.

.fail (fn)
when the error occurred will call
msg is supposed to print the error
err supposed to throw an error
yargs is yargs examples

var argv = require('yargs')
  .fail(function (msg, err, yargs) {
    if (err) throw err // preserve stack
    console.error('You broke it!')
    console.error(msg)
    console.error('You should be doing', yargs.help())
    process.exit(1)
  })
  .argv

.getCompletion (args, done);
allows the program step by obtaining supplemental contents
args: command line needs to be complemented array
done: the callback function, the function will get the current supplemental contents

require('yargs')
  .option('foobar')
  .option('foobaz')
  .completion()
  .getCompletion(['./test.js', '--foo'], function (completions) {
    console.log(completions)
  })
  //如果输入 ./test.js --foo 输入TAB: --foobar 和 --foobaz

.global (globals, [global = true
]) This command guidance of an option will not be reset when the command execution time

var argv = require('yargs')
  .option('a', {
    alias: 'all',
    default: true,
    global: false
  })
  .option('n', {
    alias: 'none',
    default: true,
    global: false
  })
  .command('foo', 'foo command', function (yargs) {
    return yargs.option('b', {
      alias: 'bar'
    })
  })
  .help('help') 
  .Global ( 'A' ) 
  .argv 

  // if foo execution, all the parameters will be retained, but the node will be deleted

.group (key (s), groupName
) to a key or a set of keys into a groupName, the time when calls are grouped using a document showing

var yargs = require('yargs')(['--help'])
  .help()
  .group('batman', 'Heroes:')
  .describe('batman', "world's greatest detective")
  .wrap(null)
  .argv

//结果:
//  Heroes:
//  --batman  world's greatest detective

//Options:
//  --help  Show help  [boolean]

.help ([option, [description]
]) set Helpful hints
If you do not pass parameters, .help (); where this option is enabled --help

var yargs = require("yargs")(['--info'])
  .usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
  .help('info')
  .argv

.implies (x, y)
if the set x, then y must be set

.locale ()
returns yargs currently in use

middleware (callbacks, [applyBeforeValidation])
defined middleware

.nargs (key, count)
represented by this method, the number of parameters which later

var argv = require('yargs')
  .nargs('token', 1)
  .parse(['--token', '-my-token']);

  //{ _: [], token: '-my-token', '$0': 'node test' }

.normalize (key)
is said to be in order when the incoming path for easy call path.normalize ()

.number (key)
told parser, this has been the key as a digital conversion

Parameter can be an array

If the option is not, default is undefined

Can not be converted to digital, it will be converted to NaN

Decimal, hexadecimal, scientific notation is legal

var argv = require("yargs")
  .number("n")
  .number(["width", "height"]).argv;

.option(key, [opt]) .options(key, [opt])

为key配置各种选项的命令
var argv = require("yargs").option("f", {
  alias: "file",
  demandOption: true,
  default: "/etc/passwd",
  describe: "x marks the spot",
  type: "string"
}).argv;
//同
var argv = require("yargs")
  .alias("f", "file")
  .demandOption("f")
  .default("f", "/etc/passwd")
  .describe("f", "x marks the spot")
  .string("f").argv;
  //同
  var argv = require("yargs").options({
  f: {
    alias: "file",
    demandOption: true,
    default: "/etc/passwd",
    describe: "x marks the spot",
    type: "string"
  }
}).argv;

There are those available key

  • alias
  • array
  • boolean
  • choices
  • coerce
  • config
  • configParser
  • conflicts
  • count
  • default
  • defaultDescription
  • demandOption
  • desc/describe/description
  • global
  • group
  • hidden
  • implies
  • Nargis
  • normalize
  • number
  • requiresArg
  • skipValidation
  • string
  • type: ‘array’,’boolean’,’count’,’number’,’string’

.parse([args], [context], [parseCallback])

Alternative parameters can be transmitted from process.argv, argv returned object. args an array may be native or parameter string.

context: an object parameter can simultaneously carry, can provide status information for the command, is a very practical technology.

const parser = yargs
  .command(
    "lunch-train <restaurant>",
    "start lunch train",
    function() {},
    function(argv) {
      console.log(argv.restaurant, argv.time);
    }
  )
  .parse("lunch-train rudy's", { time: "12:15" });

  

parseCallback : This method callback function, will carry three parameters

validation errors occurring in conversions: ERR
the argv: the argv object into the
text to be output at the terminal: output

const parser = yargs
  .command(
    "lunch-train <restaurant> <time>",
    "start lunch train",
    function() {},
    function(argv) {
      api.scheduleLunch(argv.restaurant, moment(argv.time));
    }
  )
  .help();

parser.parse(bot.userText, function(err, argv, output) {
  if (output) bot.respond(output);
});

.pkgConf (key, [cwd])
similar .config (), which indicates a specific configuration yargs find the object from package.json
cwd can be selectively provided, read from here package.json

.scriptName ($ 0)
Set the name of the executable file, $ 0

var yargs = require("yargs")
.scriptName("my-script")
.help()
.argv

 

.wrap (columns)
Set the column

.showHelp(consoleLevel=’error’)

With the console consoleLevelusing data printing 

 

var yargs = require("yargs").usage(
  "$0 -operand1 number -operand2 number -operation [add|subtract]"
);
yargs.showHelp(); //prints to stderr using console.error()

Alternatively, the standard print output usage information, may be selected console.log:

 

yargs.showHelp("log"); //prints to stdout using console.log()

 

Guess you like

Origin www.cnblogs.com/hellolol/p/11468787.html