官網地址: https://github.com/tj/commander.js/blob/f1ae2db8e2da01d6efcbfd59cbf82202f864b0c1/Readme_zh-CN.md
Commander.js是node.js命令行界面的完整解決方案
開始
- 新建一個node工程
- 執行 npm install commander
- package.json中新增代碼
- 添加 #! /usr/bin/env node,用于識別是node命令文件
"bin": {"cli": "./index.js"
}
聲明 program 變量
/ CommonJS (.cjs)
const { program } = require('commander');
如果程序較為復雜,用戶需要以多種方式來使用 Commander,如單元測試等。創建本地 Command 對象是一種更好的方式:
const { Command } = require('commander');
const program = new Command();
選項 option
使用 .option 實現,舉個例子,然后再解釋難點
program.option('-d, --debug', 'output extra debugging').option('-s, --small', 'small pizza size').option('-p, --pizza-type <type>', 'flavour of pizza');.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');.option('-d, --drink [item]', 'output extra debugging', function deb (v) {console.log('1---', arguments);return '123'})
- 第一個參數是選項名稱,第二個參數選項描述, 第三個參數是默認值, 第四個為過濾函數,會改改變用戶輸入的值
- 每個選項可以定義一個短選項名稱(-后面接單個字符)
- 一個長選項名稱(–后面接一個或多個單詞),駝峰命名法(camel-case)
- 短名稱和長名稱之間可以使用逗號,空格,|分割
- 有兩種最常用的選項
- 一類是 boolean 型選項,選項無需配置參數,
- 另一類選項則可以設置參數(使用尖括號聲明在該選項后,如–expect )。如果在命令行中不指定具體的選項及參數,則會被定義為undefine
調用方式
serve -p 80
serve -p80
serve --port 80
serve --port=80
項及其選項參數可以用空格分隔,也可以組合成同一個參數。選項參數可以直接跟在短選項之后,也可以在長選項后面加上 = 。
完整例子
program.option('-d, --debug', 'output extra debugging').option('-s, --small', 'small pizza size').option('-p, --pizza-type <type>', 'flavour of pizza');.option('-d, --drink [item]', 'output extra debugging', function deb (v) {console.log('1---', arguments);return '123'})program.parse(process.argv);const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
必填選項
通過 .requiredOption 方法可以設置選項為必填。必填選項要么設有默認值,要么必須在命令行中輸入,對應的屬性字段在解析時必定會有賦值。該方法其余參數與 .option一致
program.requiredOption('-c, --cheese <type>', 'pizza must have cheese');program.parse();終端中部署入參數,會報錯
error: required option '-c, --cheese <type>' not specified
變長參數選項
通過使用 … 來設置參數為可變長參數
program.option('-n, --number <numbers...>', 'specify numbers').option('-l, --letter [letters...]', 'specify letters');program.parse();console.log('Options: ', program.opts());
console.log('Remaining arguments: ', program.args);
$ collect -n 1 2 3 --letter a b c
Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
Remaining arguments: []
$ collect --letter=A -n80 operand
Options: { number: [ '80' ], letter: [ 'A' ] }
Remaining arguments: [ 'operand' ]
$ collect --letter -n 1 -n 2 3 -- operand
Options: { number: [ '1', '2', '3' ], letter: true }
Remaining arguments: [ 'operand' ]
其他選項配置
大多數情況下,選項均可通過.option()方法添加。但對某些不常見的用例,也可以直接構造Option對象,對選項進行更詳盡的配置
program.addOption(new Option('-s, --secret').hideHelp()).addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute')).addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large'])).addOption(new Option('-p, --port <number>', 'port number').env('PORT')).addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat)).addOption(new Option('--disable-server', 'disables the server').conflicts('port')).addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));
版本選項
.version 方法可以設置版本,其默認選項為-V和–version,設置了版本后,命令行會輸出當前的版本號
program.version('0.0.1');
命令
通過 .command 或 .addCommand 可以配置命令, 有兩種實現方式
- 為命令綁定處理函數
- 將命令單獨寫成一個可執行文件
先看例子
// 通過綁定處理函數實現命令(這里的指令描述為放在`.command`中)
// 返回新生成的命令(即該子命令)以供繼續配置
program.command('clone <source> [destination]').description('clone a repository into a newly created directory').option('-t, --typeName <typeName>', '基于哪個項目').action((source, destination) => {console.log('clone command called');});// 通過獨立的的可執行文件實現命令 (注意這里指令描述是作為`.command`的第二個參數)
// 返回最頂層的命令以供繼續添加子命令
program.command('start <service>', 'start named service').command('stop [service]', 'stop named service, or all if no name supplied');// 分別裝配命令
// 返回最頂層的命令以供繼續添加子命令
program.addCommand(build.makeBuildCommand());
- .command 的第一個參數為命令名稱, 命令參數可以跟在名稱后面,也可以用.argument 單獨指定, 參數可為必選的(尖括號表示)、可選的(方括號表示)或變長參數(點號表示,如果使用,只能是最后一個參數)
- option 為命令中的選項 比如 vue create my-project -t vue-template
- .description 為命令描述
- .action 為命令觸發之后,執行的函數
舉個例子:
program.command('rmdir <soure>').description('remove some directory').option('-f, --force', '強制刪除').action((source, destination) => {console.log('remove some directory');});
// 調用方式
// Try the following:
// rmdir ./project
// rmdir ./project -f
// rmdir ./project --forceprogram.command('add').argument('<first>', 'integer argument', myParseInt).argument('[second]', 'integer argument', myParseInt, 1000).action((first, second) => {console.log(`${first} + ${second} = ${first + second}`);});
// 調用方式
// Try the following:
// add 1
// add 1 2program.argument("<name>").option("-t, --title <honorific>", "title to use before name").option("-d, --debug", "display some debugging").action((name, options, command) => {if (options.debug) {console.error("Called %s with options %o", command.name(), options);}const title = options.title ? `${options.title} ` : "";console.log(`Thank-you ${title}${name}`);});// 調用方式
// Try the following:
// node thank.js John
// node thank.js Doe --title Mr
// node thank.js --debug Doe --title Mr