はじめに
node.jsでbatch処理書くって言っても、普通にnode batch.jsとかで実行したらええんじゃないの?visionmedia/commander使って引数渡したらいいんじゃないのって話ではないです。visionmedia/batch
https://github.com/visionmedia/batchcommanderは超重宝するのでもちろん使ったほうがいいのですが、その中の処理を非同期に書いたり、progressの処理が書けたりするので便利。
使い方
package.jsonに"batch"を追記して、npm install。
実装はこんな感じ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Batch = require('batch') | |
, batch = new Batch; | |
var self = this; | |
batch.concurrency(4); | |
var ids = [0,1,2,3]; | |
var fleetName = ['加賀', '赤城', '島風', '出雲']; | |
function organizeFleet(id, done) { | |
var fleet = fleetName[id]; | |
console.log('organized', fleet); | |
done(null, fleet); | |
} | |
ids.forEach(function(id) { | |
batch.push(function(done) { | |
organizeFleet(id, done); | |
}); | |
}); | |
batch.on('progress', function(e) { | |
console.log('progress', e.complete / e.total * 100, '%'); | |
}); | |
batch.end(function(err, fleets) { | |
console.log('results', fleets); | |
}); |
実行するとこんな感じ。
$ node batch.js
organized 加賀
progress 25 %
organized 赤城
progress 50 %
organized 島風
progress 75 %
organized 出雲
progress 100 %
results [ '加賀', '赤城', '島風', '出雲' ]
batch.push()したfunctionがbatch.end()でconcurrencyされた数で並行に実行されてるみたい。
resultsはdone()で2つ目の引数で渡した値がpushされていくみたいですね。
resultsはdone()で2つ目の引数で渡した値がpushされていくみたいですね。
progressの中身はこんなことになっています。
これ使って現在どこまで処理してるか〜とかをconsole.logに書いたりするなど色々使えますね。
{ index: 0,
value: '加賀',
error: null,
pending: 4,
total: 4,
complete: 1,
percent: 25,
start: Wed Aug 07 2013 19:36:49 GMT+0900 (JST),
end: Wed Aug 07 2013 19:36:49 GMT+0900 (JST),
duration: 11 }
まとめ
艦これのコンテンツ力…!!
0 件のコメント:
コメントを投稿