public
Created

How to do domains...

  • Download Gist
domain-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
// based on an example by @mikeal
 
var http = require('http')
, domain = require('domain')
;
 
module.exports = function (handler) {
var server = http.createServer(function (req, resp) {
var d = domain.create()
// add these to the domain
// explicitely so they dont
// get mixed into other domains
domain.add(req)
domain.add(resp)
d.run(function () {
handler(req, resp)
})
d.on('uncaughtException', function (e) {
// cleanup io, end streams
// don't cascade to the server
// or root domain
d.dispose()
d.once('dispose', function () {
// give a chance for streams
// and other things to end
// gracefully - eg. remove a half
// written file, rollback a transaction
process.exit()
})
})
d.on('error', function (err) {
console.error(err)
resp.statusCode = 500
resp.end()
if(d.listeners('error').length == 1) {
d.emit('uncaughtException', err)
}
})
})
return server
}

@izs how important is it to call dispose() in this case?

@ritch it's not a given that you should bring down the process.

True, also dispose() shouldn't be a given. Updated to wrap those in an uncaughtException event.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.