# Commander.js
[](http://travis-ci.org/tj/commander.js)
[](https://www.npmjs.org/package/commander)
[](https://npmcharts.com/compare/commander?minimal=true)
[](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander --save
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.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);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.parse(process.argv);
console.log('you ordered a pizza');
if (program.sauce) console.log(' with sauce');
else console.log(' without sauce');
```
## Version option
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.
$ ./examples/pizza -V
0.0.1
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
```js
program
.version('0.0.1', '-v, --version')
```
The version flags can be named anything, but the long option is required.
## Command-specific options
You can attach options to a command.
```js
#!/usr/bin/env node
var program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmd) {
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
## Coercion
```js
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.1.0')
.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);
```
## Regular Expression
```js
program
.version('0.1.0')
.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);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.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);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.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");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.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);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the option from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
## Automated --help
The help information is auto-generated based on the information commander already knows about yo


星川皆无恙
- 粉丝: 1w+
- 资源: 54
最新资源
- 基于LCL滤波的光伏PV三相并网逆变器MATLAB仿真研究:集成MPPT控制、坐标变换与功率解耦控制技术实现高效同步输出,基于LCL滤波的光伏PV三相并网逆变器MATLAB仿真研究:MPPT控制与dq
- 基于电气工程视角的光伏并网系统研究:单相与三相逆变技术、电能质量改善及配电网影响分析,电气工程领域的研究:光伏并网、三相逆变、电能质量分析与有源滤波器谐波检测及其对配电网继电保护的影响及实践研究 ,光
- 蓝桥杯单片机-第十三届省赛(第一场)
- STM32低压无感BLDC方波控制方案:快速启动、多保护机制与源码全支持,专业资料齐全,STM32低压无感BLDC方波控制方案:快速启动、电感法脉冲注入、多环路控制及全面保护功能,源码原理图全包含,s
- 基于53#三菱PLC与组态王系统的音乐喷泉控制系统设计与组态设计探讨,基于53#三菱PLC的组态王音乐喷泉控制系统设计与实现:音乐喷泉组态设计的探索与实践,53#三菱PLC和组态王音乐喷泉控制系统设计
- 基于Msp430设计的环境监测系统(完整系统源码等资料)实物仿真.zip
- 基于PFC2D模拟的层理岩体单级与分级蠕变行为研究:剪切蠕变效应的数值分析,基于PFC2D模拟的层理岩体单级及分级蠕变特性研究-剪切蠕变模拟与分析,PFC2D层理岩体单级 分级蠕变(含剪切蠕变模拟)
- python-43.创建协程任务(异步编程)-还可以更快一点吗.py
- C#驱动的SMT轨迹导入程序:高效生成DXF文件至G代码,SMT轨迹DXF文件导入与G代码生成程序:基于C#语言实现,SMT轨迹导入程序,C#导入CAD的DXF文件,生成G代码, ,SMT轨迹导入程序
- python-44.使用协程执行多个耗时任务-不过些许时光罢了.py
- 基于Matlab的SPEI干旱指数计算与多时间尺度nc tif数据融合分析(2000-2023),利用MATLAB计算SPEI干旱指数:分析多时间尺度nc tif数据(2000-2023),matla
- python-45.模拟无人机指令控制程序-开始飞机漂移.py
- Matlab中基于光伏加蓄电池的发电系统Simulink仿真模型研究,Matlab Simulink光伏加蓄电池发电系统仿真模型研究,Matlab光伏加蓄电池发电系统simulink仿真模型 ,Mat
- 基于STM32的室内智能加湿器20250215
- 基于N-K安全约束的风电-光伏-光热电站联合调度优化模型研究:仿真测试与效果分析,基于N-K安全约束的风电-光伏-光热电站联合优化调度模型:调度灵活性、经济性及其风光消纳作用分析,含风电-光伏-光热电
- 基于元胞自动机法的枝晶生长模拟:任意角度偏心正方算法结合流体动力学LBM研究,基于元胞自动机法的枝晶生长模拟:任意角度偏心正方算法结合流体动力学LBM分析,C++程序,基于元胞自动机法模拟枝晶生长,能
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


