總體介紹:
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