minimist是个朴素实用的解析命令行参数的工具。之前用yargs,但对于没有命令行指令的需求来说,用yargs太重了。
const minimist = require('minimist'); const argv = minimist(process.argv.slice(2)); console.log(argv); // node minimist.js -a beep -b boop // { _: [], a: 'beep', b: 'boop' } // node minimist.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' }
支持options:string,boolean,alias,default都是自解释选项,不赘述。opts.stopEarly:只将第一个参数放入argv._里。opts[‘–‘]:将所有在–双连线前的参数放入argv._里,将所有在–双连线后的参数放入argv[‘–‘]里:
const minimist = require('minimist'); const params = 'one two three -- four five --six'.split(' '); // [ 'one', 'two', 'three', '--', 'four', 'five', '--six' ] const argv2 = minimist(params, { string: true }); console.log(argv2); // node minimist.js // { _: [ 'one', 'two', 'three', 'four', 'five', '--six' ] } const argv3 = minimist(params, { '--': true }); console.log(argv3); // node minimist.js // { _: [ 'one', 'two', 'three' ], '--': [ 'four', 'five', '--six' ] }