How to use Node.js 0.8.x domains with express?

后端 未结 5 589
旧时难觅i
旧时难觅i 2021-02-01 19:34

How can I create Express/Connect middleware which wrap each request in its own domain?

5条回答
  •  清歌不尽
    2021-02-01 19:41

    This is a late answer, but check out the express-domain-moddleware module. It automatically creates a new domain for each request. The active domain can be referenced by process.domain in your routes. Here is an example:

    //with domain-middleware
    app.use(require('express-domain-middleware'));
    app.use(app.router);
    
    app.use(function errorHandler(err, req, res, next) {
      console.log('error on request %d %s %s: %j', process.domain.id, req.method, req.url, err);
      res.send(500, "Something bad happened. :(");
      if(err.domain) {
        //you should think about gracefully stopping & respawning your server
        //since an unhandled error might put your application into an unknown state
      }
    });
    
    app.get('/error', function(req, res, next) {
      db.query('SELECT happiness()', process.domain.intercept(function(rows) {
        fs.readFile('asldkfjasdf', process.domain.intercept(function(contents) {
          process.nextTick(process.domain.intercept(function() {
            throw new Error("The individual request will be passed to the express error handler, and your application will keep running.");
          }));
        }));
      }));
    });
    

提交回复
热议问题