Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Combining cluster and node-http-proxy for part master and part worker http responses
var cluster = require('cluster'),
http = require('http'),
httpProxy = require('http-proxy');
var httpPort = 4332;
var clusterSock = './cluster.sock';
var httpServer = http.createServer(function (req, res) {
res.end('Worker! ' + process.pid);
});
var cl = cluster(httpServer)
.set('workers', 5)
.listen(clusterSock);
if (cl.isMaster) {
var options = {
target: { host: 'localhost', port: clusterSock }
};
httpProxy.createServer(options, function (req, res, proxy) {
if (Date.now() % 10 < 5) {
console.log('Relaying to worker');
proxy.proxyRequest(req, res);
} else {
console.log('Master response');
res.end('Master! ' + process.pid);
}
}).listen(httpPort);
console.log('HTTP proxy listening on port', httpPort);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment