如何用快捷方式使用Node.js的0.8.x域名? [英] How to use Node.js 0.8.x domains with express?

查看:127
本文介绍了如何用快捷方式使用Node.js的0.8.x域名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

更新: 下面描述的方法已在连接域 NodeJS模块中实现,该模块可以在Connect或Express应用程序中使用。



从Express 3开始, express.createServer 已被弃用,其回调应转换为中间件。在中间件中,重要的是将请求和结果对象添加到请求域,以便它们触发的错误由域错误处理程序处理。



我的中间件看起来像像这样:

  var domain = require('domain'); 

app.use(function(req,res,next){
var requestDomain = domain.create();
requestDomain.add(req);
requestDomain .add(res);
requestDomain.on('error',next);
requestDomain.run(next);
});

如果您致电,您可以避免将请求和响应添加到请求域中http.createServer ,但是域文档似乎表明每个请求域是最佳做法。



请注意,上述代码不会执行任何域清理操作,例如强制处理请​​求域。我的中间件选择通过中间件堆栈再次传递错误,以便稍后由特定的错误处理中间件处理。 YMMV。


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

解决方案

UPDATE: The approach described below has been implemented in the connect-domain NodeJS module, which can be used in either Connect or Express applications.

As of Express 3, express.createServer is deprecated, and its callback should be converted to a middleware. In the middleware, it's important to add the request and result objects to the request domain so that errors fired by them are handled by the domain error handler.

My middleware looks something like this:

var domain = require('domain');

app.use(function(req, res, next) {
    var requestDomain = domain.create();
    requestDomain.add(req);
    requestDomain.add(res);
    requestDomain.on('error', next);
    requestDomain.run(next);
});

You can avoid adding the request and response to a request domain if you call http.createServer from within a top-level domain, but the Domain docs seem to indicate that per-request domains are a best practice.

Note that the code above doesn't do any domain clean up actions, such as forcibly disposing the request domain. My middleware chooses instead to pass the error through the middleware stack again to be handled by specific error-handling middleware later on. YMMV.

这篇关于如何用快捷方式使用Node.js的0.8.x域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆