node 第三方模块系列------minimist轻量级的命令行参数解析引擎

总体介绍:

node.js的命令行参数解析工具有很多,比如:argparse、optimist、yars、commander。optimist和yargs内部使用的解析引擎正是minimist,代码量也很少(只有几百行),非常适合研读。

使用api

let parseArgs = require('minimist')
let argv = parseArgs(args, opts={})

实例:

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);

运行结果:

$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }


$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  beep: 'boop' }

api说明:从上面的实例可以看出

带有“-”或者“--”的参数都被解析成单独的key值,也就是独立的参数,而不带有参数选项的参数会被统一解析到 _ 数组中

关于options

options can be:

  • opts.string - a string or array of strings argument names to always treat as strings
  • opts.boolean - a boolean, string or array of strings to always treat as booleans. if true
    will treat all double hyphenated arguments without equal signs as boolean (e.g. affects --foo, not -f or --foo=bar)
  • opts.alias - an object mapping string names to strings or arrays of string argument names to use as aliases
  • opts.default - an object mapping string argument names to default values
  • opts.stopEarly - when true, populate argv._ with everything after the first non-option
  • opts['--'] - when true, populate argv._ with everything before the -- and argv['--']
    with everything after the --. Here's an example:
  • opts.unknown - a function which is invoked with a command line parameter not defined in the opts configuration object. If the function returns false, the unknown option is not added to argv.


实例:

require('./')('one two three -- four five --six'.split(' '), { '--': true })
{ _: [ 'one', 'two', 'three' ],
'--': [ 'four', 'five', '--six' ] }

参考:

https://www.jianshu.com/p/231b931ab389

https://www.jianshu.com/p/c5a46a076fad

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值