commander 中文文档 commander Dome 安装 常用 api .version('x.y.z') 用于设置命令程序的版本号 .option('-n, --name ', 'your name', 'GK') 用来定义带选项的 commander,同时也作为这些选项的文档 第一个参数是选项定义,用|,,,连接 参数可以用<>或者[]修饰,前者意为必须参数,后者意为可选参数 第二个参…

commander 中文文档

commander Dome

安装

npm install commander

常用 api

  1. .version('x.y.z')

    用于设置命令程序的版本号

// index.js
var program = require('commander');
program.version('0.0.1');
program.parse(process.argv);
node index.js -V
# 输出
# 0.0.1
  1. .option('-n, --name ', 'your name', 'GK')

    用来定义带选项的 commander,同时也作为这些选项的文档

    1. 第一个参数是选项定义,用|,,,连接
      1. 参数可以用<>或者[]修饰,前者意为必须参数,后者意为可选参数
    2. 第二个参数为选项描述
    3. 第三个参数为选项参数默认值,可选
var program = require('commander');
program
  .version('0.0.1')
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-a, --age <age>', 'your age', '18')
  .option('-b, --bbq-sauce', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]')
  .parse(process.argv);
if (program.peppers) console.log('输入了peppers', program.peppers);
if (program.pineapple) console.log('输入了pineapple', program.pineapple);
if (program.bbqSauce) console.log('输入了bbqSauce', program.bbqSauce);
if (program.age) console.log('输入了age', program.age);
if (program.cheese) console.log('输入了acheese', program.cheese);
node index.js -p
# 输入了peppers true
# 输入了age 18
node index.js -P
# 输入了pineapple true
# 输入了age 18
node index.js -a 22
# 输入了age 22
node index.js -b
# 输入了bbqSauce true
# 输入了age 18
node index.js -c life
# 输入了age 18
# 输入了acheese life
  1. .command('init ', 'description')

    一个命令的最后一个参数可以是可变参数, 并且只有最后一个参数可变。为了使参数可变,你需要在参数名后面追加 ...

    1. 第一个参数是命定定义,可以使用<>和[]修饰命令参数
    2. 第二个参数是命令描述
      1. 当没有第二个参数的时候,commander.js 将返回 Command 对象,若有第二个参数,将返回原型对象
      2. 当带有第二个参数,并且没有显示调用 action(fn)时,则将会使用子命令模式
      3. 所谓子命令模式即:./pm,./pm-install,./pm-search 等。这些子命令跟主命令在不同的文件中。
// index.js
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')
  .description('run remote setup commands')
  .action(function() {
    console.log('setup');
  });
program
  .command('exec <cmd>')
  .description('run the given remote command')
  .action(function(cmd) {
    console.log('exec "%s"', cmd);
  });
program
  .command('teardown <dir> [otherDirs...]')
  .description('run teardown commands')
  .action(function(dir, otherDirs) {
    console.log('dir "%s"', dir);
    if (otherDirs) {
      otherDirs.forEach(function(oDir) {
        console.log('otherDirs "%s"', oDir);
      });
    }
  });
program
  .command('*')
  .description('deploy the given env')
  .action(function(env) {
    console.log('deploying "%s"', env);
  });
program.parse(process.argv);
node index2.js setup
#  输出 setup
node index2.js exec i
# 输出 exec "i"
node index2.js teardown ./index.js ./index2.js
# 输出 dir "./index.js"
# 输出 otherDirs "./index2.js"
node index2.js *
# 输出deploying "[object Object]"
  1. .outputHelp(cb)

    不退出输出帮助信息。 可选的回调可在显示帮助文本后处理。 如果你想显示默认的帮助(例如,如果没有提供命令),你可以使用类似的东西:

// index.js
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); // 在控制台上显示红色的帮助文本
}
# 因为command第二个参数存在,所以就会使用子命令模式 index-getstream
node index.js getstream

demo

使用 commander 实现在执行目录下生成一个.npmrc 文件,用使用默认的 registry、disturl、loglevel 配置,源代码

package.json

{
  "name": "npmrc-local",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "bin": {
    "npmrc": "./bin/npmrc.js"
  },
  "directories": {
    "lib": "lib"
  },
  "scripts": {
    "start": "node ./bin/npmrc.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "commander": "^2.20.0"
  }
}

rc.js

module.exports = {
  registry: 'https://registry.npm.taobao.org/',
  disturl: 'http://npm.taobao.org/mirrors/node/',
  loglevel: 'http'
};

bin/npmrc.js

require('../lib/index');

lib/index.js

var fs = require('fs');
var path = require('path');
var readline = require('readline');
var program = require('commander');
var rc = require('../rc');
var exit_bak = process.exit;
program
  .version('0.0.1')
  .allowUnknownOption()
  .option('-r, --registry <registry>', 'use custom registry', rc.registry)
  .option('-d, --dist-url <disturl>', 'use custom dist url', rc.disturl)
  .option('-l, --log-level <loglevel>', 'use custom log level', rc.loglevel);
program.parse(process.argv);
program.registry && (rc.registry = program.registry);
program.distUrl && (rc.disturl = program.distUrl);
program.logLevel && (rc.loglevel = program.logLevel);
if (!_exit.exited) {
  _main();
}
// Graceful exit for async STDIO
function _exit(code) {
  var draining = 0;
  var streams = [process.stdout, process.stderr];

  function done() {
    if (!draining--) {
      exit_bak(code);
    }
  }
  _exit.exited = true;
  streams.forEach(function(stream) {
    draining += 1;
    stream.write('', done);
  });
  done();
}

function _confirm(msg, cb) {
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question(msg, function(input) {
    rl.close();
    cb(/^y|yes|ok|true$/i.test(input));
  });
}

function _write(path, content, mode) {
  fs.writeFileSync(path, content, {
    mode: mode || 0o666
  });
  console.log('success!!!');
}

function _generateFile(filePath) {
  var content = 'registry={registry}\ndisturl={disturl}\nloglevel={loglevel}\n';
  content = content.replace(/\{(\w+)\}/gi, function(a, b) {
    return rc[b];
  });
  _write(filePath, content);
}

function _overwrite(filePath) {
  _generateFile(filePath);
}

function _existNpmRC(filePath) {
  fs.exists(filePath, function(exists) {
    if (exists) {
      _confirm('ATTENTION: .npmrc is exist, over write? [y/N] ', function(ans) {
        ans ? _overwrite(filePath) : console.log('bye!');
      });
    } else {
      _generateFile(filePath);
    }
  });
}

function _main() {
  var filePath = path.resolve(process.cwd(), '.npmrc');
  console.log('writing path: ' + filePath);
  _existNpmRC(filePath);
}

bash语句

npm start
# writing path: D:\Web\node-study\node-cmd\npmrc-local\.npmrc
# uccess!!!

当前执行目录下生成 .npmrc

registry=https://registry.npm.taobao.org/
disturl=http://npm.taobao.org/mirrors/node/
loglevel=http

暂无评论