node.jsをサーバサイドスクリプトとして使用する場合、
どうせならcronで処理するようなバッチもnode.jsで書きたいじゃないですか。
で、node.jsを引数付きで実行する場合、process.argvなんかもあるんですが、
良いモジュールを見つけましたので、
こちらを使ったテストバッチを書いてみました。
参考:visionmedia / commander.js
まずはcommander.jsのインストール
npm install commander
次にバッチコマンドの作成をします。
#!/usr/bin/env node
/**
* @description
* test batch
* @author dommy <shonan.shachu at gmail.com>
*/
// to use node commander module
// $npm install commander
var command = require('commander');
// function to split list items
function list(val) {
return val.split(',');
}
// parse command options
// create help command automatically
command
.version('1.0.0')
.usage('[option]')
.option('-i, --integer <n>', 'integer', parseInt)
.option('-f, --float <n>', 'float', parseFloat)
.option('-s, --string [String]', 'string')
.option('-l, --list <items>', 'List devided by ","', list)
// to make batch better, include execute or force option
.option('-e, --exec', 'force to execute the batch')
.parse(process.argv);
if(command.integer) console.log('integer : ' + command.integer);
if(command.float) console.log('float : ' + command.float);
if(command.string) console.log('string : ' + command.string);
if(command.list) console.log('list : ' + JSON.stringify(command.list));
if(command.exec) console.log('exec : ' + command.exec);
こんな感じで、処理は表示させるだけのバッチを作成しました。
では、実行してみます。
dommy$ ./batch.js -i 12345 -f 12.345 -s string -l 105,shonan -e integer : 12345 float : 12.345 string : string list : ["105","shonan"] exec : true
引数通りの結果が得られました。
次に、このバッチのhelpを見てみましょう。
dommy$./batch.js --help
Usage: batch.js [option]
Options:
-h, --help output usage information
-V, --version output the version number
-i, --integer <n> integer
-f, --float <n> float
-s, --string [String] string
-l, --list <items> List devided by ","
-e, --exec force to execute the batch
と、helpも自動生成してくれます。

0 件のコメント:
コメントを投稿