Skip to content

Instantly share code, notes, and snippets.

@LinusU
Last active August 29, 2015 14:15
Show Gist options
  • Save LinusU/7eebf8fbf845d3512628 to your computer and use it in GitHub Desktop.
Save LinusU/7eebf8fbf845d3512628 to your computer and use it in GitHub Desktop.
Node.js cluster together with Grunt
var os = require('os');
var async = require('async');
var cluster = require('cluster');
if (cluster.isWorker) {
process.on('message', function (msg) {
// Do the Phantom JS stuff
process.send(msg);
});
return ;
}
module.exports = function (grunt) {
grunt.initConfig({
Prathap: {
options : {
data: [1, 2, 3, 4, 5, 6, 7, 8],
targets: {},
target: {}
}
}
});
grunt.registerTask('Log', 'An example.', function () {
var done = this.async();
var workers = os.cpus().map(function () {
return cluster.fork();
});
var queue = async.queue(function (msg, cb) {
var worker = workers.pop();
worker.once('message', function (msg) {
workers.push(worker);
cb(null, msg);
});
worker.send(msg);
}, workers.length);
async.each([1, 2, 3, 4, 5, 6, 7, 8], queue.push.bind(queue), function (err) {
if (err) {
throw err;
}
workers.forEach(function (worker) {
worker.kill();
});
console.log('Completed');
done();
});
});
};
/*
When I run grunt Log. It's output is like below:
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Running "Log" task
Completed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment