Skip to content

Instantly share code, notes, and snippets.

@brycebaril
Forked from isaacs/domain-cluster-example.js
Created March 28, 2013 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brycebaril/5264470 to your computer and use it in GitHub Desktop.
Save brycebaril/5264470 to your computer and use it in GitHub Desktop.
var cluster = require('cluster');
var PORT = +process.env.PORT || 1337;
if (cluster.isMaster) {
// In real life, you'd probably use more than just 2 workers,
// and perhaps not put the master and worker in the same file.
cluster.fork();
cluster.fork();
cluster.on('disconnect', function(worker) {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
var domain = require('domain');
var server = require('http').createServer(function(req, res) {
var d = domain.create();
d.on('error', function(er) {
console.error('error', er.stack);
// note: we're in dangerous territory now!
try {
// make sure we close down within 30 seconds
var killtimer = setTimeout(function() {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// stop taking new requests.
server.close(function() {
console.error('server no longer listening');
});
// let the master know we're through. This will trigger a
// 'disconnect' in the cluster master, and then it will fork
// a new worker.
cluster.worker.disconnect();
// try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// oh well?
console.error('Error sending 500!', er2.stack);
}
});
// because req and res were created before this domain existed,
// we need to explicitly add them.
d.add(req);
d.add(res);
// Now run the handler function.
d.run(function() {
handleRequest(req, res);
});
});
server.listen(PORT);
}
function handleRequest(req, res) {
switch(req.url) {
case '/error':
setTimeout(function() {
// this is the error
flerb.bark();
});
break;
default:
res.end('ok');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment