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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章