Skip to content

Instantly share code, notes, and snippets.

@jmerrifield
Created March 28, 2014 21:55
Show Gist options
  • Save jmerrifield/9843820 to your computer and use it in GitHub Desktop.
Save jmerrifield/9843820 to your computer and use it in GitHub Desktop.
Sample Express app with domain wrapping
var app = require('express')()
, server = require('http').createServer(app)
app.use(function (req, res, next) {
console.log('Handling', req.path, process.pid)
var d = require('domain').create()
d.add(req)
d.add(res)
d.on('error', function (err) {
console.log('error', err)
next(err)
d.dispose()
cluster.worker.disconnect()
})
req.domain = d
d.run(next)
})
var defer = require('when').defer()
app.use(function (req, res, next) {
defer.promise.then(function () {
req.domain.run(next)
// next()
})
})
app.get('/', function (req, res) {
res.send('hello')
})
app.get('/slow', function (req, res) {
setTimeout(function () {
res.send('eventual response')
}, 10000)
})
app.get('/throw', function (req, res) {
setTimeout(function () {
throw new Error('fdsa')
}, 10)
})
server.listen(process.env.NODE_PORT, function () {
defer.resolve()
setTimeout(function () {
process.send('ready')
}, 5000)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment