DIV CSS 佈局教程網

Node.js 命令列參數的好幫手:commander 模組實戰
編輯:JavaScript綜合知識     

處理命令列參數,內建的 process.argv 當然能用,但字串解析、型別轉換、說明文件全都得自己來,寫起來相當吃力。TJ 大神寫的 commander 把這些都包好了,用起來乾淨俐落。

一、安裝

npm install commander

二、option 解析

commander 用 .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         Add the specified type of cheese [marble]
  -h, --help           output usage information

若想在說明裡補上自訂的「使用範例」,可以監聽 --help 事件:

#!/usr/bin/env node

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

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

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

// must be before .parse() since
// node's emit() is immediate
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');

注意註解裡提到的順序問題:監聽必須寫在 .parse() 之前,因為 node 的事件觸發是即時的。

四、一個較完整的例子

commander 的第三個參數可以傳入處理函式,用來把字串轉成需要的型別;帶初始值時還能做到可重複傳入與累加。

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] ')
    .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);

其中 -c, --collect 搭配初始值 [] 能收集多次傳入的值,-v, --verbose 則能做出 -vvv 這種遞增的詳細度旗標,這兩個技巧在實作 CLI 工具時非常實用。

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