public
Last active

  • Download Gist
domain-cluster-example.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
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');
}
}

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

Shouldn't line 31 be process.unref()

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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.