node.js 命令行接口的完整解決方案前端
$ npm install commander --save
複製代碼
做用:定義命令程序的版本號 用法示例:.version('0.0.1', '-v, --version') 參數解析:node
- 版本號<必須>
- 自定義標誌<可省略>:默認爲 -V 和 --version
做用:用於定義命令選項 用法示例:.option('-n, --name
', 'name description', 'default name') git參數解析:github
- 自定義標誌<必須>:分爲長短標識,中間用逗號、豎線或者空格分割;標誌後面可跟必須參數或可選參數,前者用 <> 包含,後者用 [] 包含
- 選項描述<省略不報錯>:在使用 --help 命令時顯示標誌描述
- 默認值<可省略>
做用:添加命令名稱 用法示例:.command('rmdir 正則表達式
[otherDirs...]', 'install description', opts) 參數解析:npm
- 命令名稱<必須>:命令後面可跟用 <> 或 [] 包含的參數;命令的最後一個參數能夠是可變的,像實例中那樣在數組後面加入 ... 標誌;在命令後面傳入的參數會被傳入到 action 的回調函數以及 program.args 數組中
- 命令描述<可省略>:若是存在,且沒有顯示調用action(fn),就會啓動子命令程序,不然會報錯
- 配置選項<可省略>:可配置noHelp、isDefault等
做用:自定義別名 用法 .alias('ex')數組
做用:定義命令的描述 用法示例:.description('rmdir desc')bash
做用:定義命令的回調函數 用法示例:.action(fn)app
做用:用於解析process.argv,設置options以及觸發commands 用法示例:.parse(process.argv)async
.option()
方法用來定義帶選項的 commander,同時也做爲這些選項的文檔。下面的例子會解析來自 process.argv
指定的參數和選項,沒有匹配任何選項的參數將會放到 program.args
數組中。
#!/usr/bin/env node
/** * Module dependencies. */
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
複製代碼
短標誌能夠做爲單獨的參數傳遞。像 -abc
等於 -a -b -c
。多詞組成的選項,像「--template-engine」會變成 program.templateEngine
等。
#!/usr/bin/env node
var program = require('commander');
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.0.1')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
複製代碼
program
.version('0.0.1')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
複製代碼
一個命令的最後一個參數能夠是可變參數, 而且只有最後一個參數可變。爲了使參數可變,你須要在參數名後面追加 ...
。 下面是個示例:
#!/usr/bin/env node
/** * Module dependencies. */
var program = require('commander');
program
.version('0.0.1')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
複製代碼
可變參數的值以 數組
的形式保存。如上所示,在傳遞給你的 action 的參數和 program.args
中的值都是如此。
#!/usr/bin/env node
var program = require('commander');
program
.version('0.0.1')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
複製代碼
尖括號(例如 <cmd>
)表明必填輸入,方括號(例如 [env]
)表明可選輸入。
// file: ./examples/pm
var program = require('commander');
program
.version('0.0.1')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
複製代碼
當 .command()
帶有描述參數時,不能採用 .action(callback)
來處理子命令,不然會出錯。這告訴 commander,你將採用單獨的可執行文件做爲子命令,就像 git(1)
和其餘流行的工具同樣。 Commander 將會嘗試在入口腳本(例如 ./examples/pm
)的目錄中搜索 program-command
形式的可執行文件,例如 pm-install
, pm-search
。
你能夠在調用 .command()
時傳遞選項。指定 opts.noHelp
爲 true
將從生成的幫助輸出中剔除該選項。指定 opts.isDefault
爲 true
將會在沒有其它子命令指定的狀況下,執行該子命令。
若是你打算全局安裝該命令,請確保可執行文件有對應的權限,例如 755
。
--harmony
您能夠採用兩種方式啓用 --harmony
:
#!/usr/bin/env node --harmony
。注意一些系統版本不支持此模式。--harmony
參數,例如 node --harmony examples/pm publish
。--harmony
選項在開啓子進程時會被保留。幫助信息是 commander 基於你的程序自動生成的,下面是 --help
生成的幫助信息:
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-C, --no-cheese You do not want any cheese
複製代碼
你能夠經過監聽 --help
來控制 -h, --help
顯示任何信息。一旦調用完成, Commander 將自動退出,你的程序的其他部分不會展現。例如在下面的 「stuff」 將不會在執行 --help
時輸出。
#!/usr/bin/env node
/** * Module dependencies. */
var program = require('commander');
program
.version('0.0.1')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('');
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
複製代碼
下列幫助信息是運行 node script-name.js -h
or node script-name.js --help
時輸出的:
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
複製代碼
不退出輸出幫助信息。 可選的回調可在顯示幫助文本後處理。 若是你想顯示默認的幫助(例如,若是沒有提供命令),你可使用相似的東西:
var program = require('commander');
var colors = require('colors');
program
.version('0.0.1')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); // 在控制檯上顯示紅色的幫助文本
}
複製代碼
輸出幫助信息並當即退出。 可選的回調可在顯示幫助文本後處理。
var program = require('commander');
program
.version('0.0.1')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook')
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
var mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
複製代碼
更多的 演示 能夠在這裏找到.
若有侵權,請發郵箱至wk_daxiangmubu@163.com 或留言,本人會在第一時間與您聯繫,謝謝!!