Commander Nodejs 命令行接口

1、简介

Commander.js:node.js 命令行接口的完整解决方案

https://github.com/tj/commander.js/blob/HEAD/Readme_zh-CN.md#commanderjs

2、常用示例

const program = require('commander');

program.version('1.0.1', '-V, --version', 'output the current version')
    // 定义参数 逗号前的是短名字,逗号后的是长名字,如-d, --debug
    // -d是布尔类型
    .option('-d, --debug', 'output extra debugging')
    //  -s是布尔类型
    .option('-s, --small', 'small pizza size')
    //  多词选项如"--template-engine"会被转为驼峰法program.templateEngine。
    // -p是值类型 若命令行有-p的话 必须在-p后跟参数
    // 说明:--pizza-type=test 其中=可以省略,-p tets 短名字后没有=
    // <type> 表示必填,不是布尔类型
    // [type] 可以填 也可以不填, --pizza-type 后面不填表示ture
    .option('-p, --pizza-type <type>', 'flavour of pizza')
    //  可以为选项设置一个默认值。
    .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');

//  program.parse(arguments)会处理参数,没有被使用的选项会被存放在program.args数组中。
program.parse(process.argv);

if (program.debug) console.log(program.opts());
// 打印的是一个对象 其中key都是长名字
// 如:
// { debug: true,
// small: undefined,
// pizzaType: undefined,
// cheese: 'blue' }
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(`- ${program.pizzaType}`);

// --help 是根据上述信息自动生成的。

 

猜你喜欢

转载自www.cnblogs.com/mengfangui/p/12313297.html