npm install commander
const { program } = require('commander');
const { Command } = require('commander');
const program = new Command();
program.version('0.0.2', '-vers, -V', 'output the current version')
.parse() //这个不能忘了
program
.version('0.0.1', '-vers, -V', 'output the current version')
.option('-d --debug', 'output extra debugging')
.option('-s --small', 'small pizza size')
.option('-p --pizza-type ' , 'flavour of pizza')
.option('-c --cheese ' , 'add the specified type of cheese', 'blue')
.option('--no-sauce', 'Remove sauce')
.option('--cheese ' , 'cheese flavour', 'mozzarella')
.option('--no-cheese', 'plain with no cheese')
.option('-c, --cheese [type]', 'Add cheese with optional type')
.option('-n, --number ' , 'specify numbers')
.option('-l, --letter [letters...]', 'specify letters')
.parse(process.argv)
通过program.parse(arguments)方法处理参数,没有被使用的选项会存放在program.args数组中。该方法的参数是可选的,默认值为process.argv。
写得有点乱,建议看官网跟着写案例。
program
.addOption(new Option('-s, --secret').hideHelp())
.addOption(new Option('-t, --timeout ' , 'timeout in seconds').default(60, 'one minute'))
.parse()
function myParseInt(value, dummyPrevious) {
const parseValue = parseInt(value, 10);
if(isNaN(parseValue)) {
throw new commander.InvalidOptionArgumentError('Not a number');
}
return parseValue;
}
function increaseVerbosity(dummyValue, previous) {
return previous + 1;
}
function collect(value, previous) {
console.log(value, previous)
return previous.concat([value]);
}
function commaSeparatedList(value, dummyPrevious) {
return value.split('.');
}
program
.option('-f, --float ' , 'float argument', parseFloat)
.option('-i, --integer ' , 'integer argument', myParseInt)
.option('-v --verbose', 'verbosity that can be increases', increaseVerbosity, 0)
.option('-c --collect ' , 'repeatable value', collect, [])
.option('-l --list ' , 'comma separated list', commaSeparatedList)
.parse()
const options = program.opts()
if(options.float !== undefined) console.log(`float: ${options.float}`)
if(options.integer !== undefined) console.log(`integer: ${options.integer}`)
if(options.verbose > 0) console.log(`verbosity: ${options.verbose}`)
if(options.collect.length > 0) console.log(options.collect)
if(options.list !== undefined) console.log(options.list);
node index.js -f 1e2
float: 100
node index.js --integer 2
integer: 2
node index.js -v -v -v
verbose: 3
node index.js -c a -c b -c c
[ ‘a’, ‘b’, ‘c’ ]
node index.js --list x,y,z
[ ‘x’, ‘y’, ‘z’ ]