Skip to content

Instantly share code, notes, and snippets.

@303182519
Created August 6, 2014 08:38
Show Gist options
  • Save 303182519/fdcf6952011f1c818a5e to your computer and use it in GitHub Desktop.
Save 303182519/fdcf6952011f1c818a5e to your computer and use it in GitHub Desktop.
开发命令行工具

开发命令行工具


Commander写自己的Nodejs命令

在使用Nodejs过程中,有很多包都支持全局安装,然后提供一个命令,然后在命令行我们就可以完成一些任务,像 express, grunt, bower, yeoman, reap, karma, requirejs 等。有时候,我们也需要自己开发这样的命令行工具。

commander.js,可以帮助我们简化命令行的开发。

var program = require('commander');

program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', '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.bbq) console.log('  - bbq');
console.log('  - %s cheese', program.cheese);

##commander的API

  • Option(): 初始化自定义参数对象,设置“关键字”和“描述”
  • Command(): 初始化命令行参数对象,直接获得命令行输入
  • Command#command(): 定义一个命令名字
  • Command#action(): 注册一个callback函数
  • Command#option(): 定义参数,需要设置“关键字”和“描述”,关键字包括“简写”和“全写”两部分,以”,”,”|”,”空格”做分隔。
  • Command#parse(): 解析命令行参数argv
  • Command#description(): 设置description值
  • Command#usage(): 设置usage值

##开发自定义的命令

var program = require('commander');

function range(val) {
return val.split('..').map(Number);
}

function list(val) {
return val.split(',');
}

program
.version('0.0.1')
.usage('test')
.option('-C, --chdir [value]', '设置服务器节点','/home/conan/server')
.option('-c, --config [value]', '设置配置文件','./deploy.conf')
.option('-m, --max <n>', '最大连接数', parseInt)
.option('-s, --seed <n>', '出始种子', parseFloat)
.option('-r, --range <a>..<b>', '阈值区间', range)
.option('-l, --list <items>', 'IP列表', list)

program
.command('deploy <name>')
.description('部署一个服务节点')
.action(function(name){
console.log('Deploying "%s"', name);
});

program.parse(process.argv);

console.log(' chdir - %s ', program.chdir);
console.log(' config - %s ', program.config);
console.log(' max: %j', program.max);
console.log(' seed: %j', program.seed);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);

运行

node myServer.js -c /deploy/c1/config.conf -m 20 -s 19.1 -r 12..101 -l 192.168.1.1,192.168.1.2,192.168.1.3 deploy server1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment