NodeJS Domains and expressjs

这一生的挚爱 提交于 2019-12-03 22:45:23

Getting domains working is a lot less work with this module: https://github.com/brianc/node-domain-middleware.

Other than that, while it's true that only an individual request may fail, the errors can sometimes leave your server in a bad state (leaked resources are one example), and it's considered good form to restart the server at that point. If Express's built-in error handler takes care of that, you won't be able to shut down your server yourself. Thus, one reason why it's nice to have the domain, so that you can have a nice point in your code to capture that. The above middleware does a lot in pulling that error-handling code out of your main flow and keeping it clean.

Combined with forky, things get even better.

By assigning each Express request to a separate domain, you can:

  • Get meaningful info about the error: what the query which triggered it, which user did the request, etc.

  • Give other requests some time to complete successfully before restarting the server. That's the point of this example in the node.js documentation.

However, you need to be careful, because calling a 3rd-party module like node-mysql can make you switch to a different domain without realizing it.

I always use this before calling an async module:

exports.preserveDomain = function (fun) {
  var d = process.domain;

  return function () {
    var args = arguments;

    d.run(function () {
      fun.apply(null, args);
    });
  };
};

I gave a talk about this issue. Check the slides if you're interested.

Sadly, node domains are now deprecated so you probably shouldn't use them (nor you should use this middleware) :(

https://nodejs.org/api/domain.html

To overcome this drawback I created coroutine-based library for writing asynchronous code: https://github.com/vacuumlabs/yacol. If you use this in your project, you can have all the domain goodness with quite decent semantics around it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!