总体介绍:
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 stringsopts.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 aliasesopts.default
- an object mapping string argument names to default valuesopts.stopEarly
- when true, populateargv._
with everything after the first non-optionopts['--']
- when true, populateargv._
with everything before the--
andargv['--']
with everything after the--
. Here's an example:opts.unknown
- a function which is invoked with a command line parameter not defined in theopts
configuration object. If the function returnsfalse
, the unknown option is not added toargv
.
实例:
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