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

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

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

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 19:48

    This set of slides on Speaker Deck gives a succinct overview:

    • Domains in node 0.8

    Express middleware code from the slides:

    var createDomain = require('domain').create;
    
    app.use(function(req, res, next) {
      var domain = createDomain();
    
      domain.on('error', function(err) {
        // alternative: next(err)
        res.statusCode = 500;
        res.end(err.message + '\n');
    
        domain.dispose();
      });
    
      domain.enter();
      next();
    });
    

提交回复
热议问题