DIV CSS 佈局教程網

commander 模組使用教學:讓 Node.js 命令列工具更好用
編輯:關於JavaScript     

處理命令列參數,內建的 process.argv 當然能用,但解析、驗證、產生說明文件全都得自己來,寫起來頗為不便。於是有大神寫出了 commander,好用程度完全不在一個量級。

一、安裝

npm install commander

二、option 解析

選項以 .option() 定義,這個方法同時也是說明文件的來源。下面的範例從 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', '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);

短旗標可以合併書寫,-abc 等同 -a -b -c。多單字的長旗標如 --template-engine 會轉成駝峰式,對應到 program.templateEngine。

三、自動產生 help 訊息

$ ./examples/pizza --help

  Usage: pizza [options]

  Options:

    -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]
    -h, --help           output usage information

也可以手動擴充說明內容:

#!/usr/bin/env node

var program = require('../');

program
  .version('0.0.1')
  .option('-f, --foo', 'enable some foo')
  .option('-b, --bar', 'enable some bar')
  .option('-B, --baz', 'enable some baz');

// 必須放在 .parse() 之前,因為 node 的 emit() 是立即的
program.on('--help', function () {
  console.log('  Examples:');
  console.log('');
  console.log('    $ custom-help --help');
  console.log('    $ custom-help -h');
  console.log('');
});

program.parse(process.argv);

console.log('stuff');

四、較完整的範例

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);

這裡最值得學的是「轉換函數」的用法:第三個參數傳入 parseInt、range 或 collect,就能在解析階段直接把字串變成需要的型別,甚至支援同一選項重複傳入並收集成陣列。後續若改用新版 commander,API 已更名為 program.option() 搭配 program.parse() 的 options 物件,但整體設計思路一致。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved