Skip to content

@isaacs /domain-cluster-example.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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');
}
}
@isaacs
Owner

This was added to the node documentation as well: http://api.nodejs.org/domain.html

@knowlecules

Shouldn't line 31 be process.unref()

@machunter

i have inherited some code which was kindly copied and not understood. the problem is that the system runs v0.8.26 (must), I noticed that the line 31 was throwing an error and when i checked the api for time in v0.8.26 i saw that unref() is not a method of a timer. My question, is there any harm removing that line? (I don't think so but I figured I would ask)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.