Skip to content

Instantly share code, notes, and snippets.

@ritch
Created October 4, 2012 14:38
Show Gist options
  • Save ritch/3833934 to your computer and use it in GitHub Desktop.
Save ritch/3833934 to your computer and use it in GitHub Desktop.
How to do domains...
// 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
}
@mikeal
Copy link

mikeal commented Oct 4, 2012

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

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

@ritch
Copy link
Author

ritch commented Oct 4, 2012

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment