# CommanderJS

# 这是什么

node.js 命令行接口的完整解决方案,灵感来自 Ruby 的 commander

# 使用

# 安装

npm install commander

# 基本的示例

const { program } = require('commander');
program.version('0.0.1');

//or
const { Command } = require('commander');
const program = new Command();
program.version('0.0.1');

# 参数

# Option

定义命令的选项说明

通常的选项类型有三种:

  • 选项类型: boolean(选项后面不跟值)
  • 选项类型: 跟一个值(使用尖括号声明)
  • 选项类型: 跟一个可选值(使用方括号声明)
const { program } = require('commander');

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 cheese with optional type');

program.parse(process.argv);

if (program.debug) console.log(program.opts());
console.log('pizza details:');
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(`- ${program.pizzaType}`);
if (program.cheese === undefined) console.log('no cheese');
else if (program.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${program.cheese}`);

设置默认值 最后一个参数即为默认值

program
  .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');

自定义函数处理

function increaseVerbosity(dummyValue, previous) {
  return previous + 1;
}

program
  .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0);

必需的选项 .requiredOption

program
  .requiredOption('-c, --cheese <type>', 'pizza must have cheese');

# Command

.command()

program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
  .action((source, destination) => {
    console.log('clone command called');
  });

操作处理程序

program
  .command('rm <dir>')
  .option('-r, --recursive', 'Remove recursively')
  .action(function (dir, cmdObj) {
    console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))
  })

独立的可执行命令

// file: ./examples/pm
const program = require('commander');

program
  .version('0.1.0')
  .command('install [name]', 'install one or more packages')
  .command('search [query]', 'search with optional query')
  .command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'})
  .command('list', 'list packages installed', {isDefault: true})
  .parse(process.argv);

默认的命令

program
  .command('serve', { isDefault: true })

# 示例

examples (opens new window)

# 学习资源

陕ICP备20004732号-3