How do domain nodes actually work behind the scenes for multiple requests?

In my case of using the node.js domain, I need to exchange information between server files at the request level.

An example implementation in express.js

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

More Explanations at Nodes Domains Explicit Binding

In the controller / service - process.domain will provide you with the above created domain And you can easily bind the values ​​to this domain. For instance,

 process.domain.obj = {}; 

This explanation is sufficient to understand the use of domains.

Questions

  • Can I use domains for multiple requests?

  • How to ensure that process.domain is different for different requests, and not the same?

I would also like to know how these problems are handled in the continuation of local storage.

+5
source share
1 answer

A warning

First of all, the domains are outdated and will be removed in the upcoming version of NodeJS. I would not write new code using them.

How do domains work?

Secondly, it’s important to understand that domains are not magical. This is a really simple concept. They are mainly:

  • Wrap each asynchronous call in the platform (all NodeJS APIs).
  • Set the "global" variable for the duration of the call.
  • If another asynchronous call is made during this call, save the note to set the global variable to the same value as you enter it.
  • What is it.

Here, how domains can be implemented, let them only implement it for setTimeout for simplicity.

 const oldTimeout = setTimeout; setTimeout = function(fn, ms) { // also ...args, but let ignore that var trackedDomain = domain; oldTimeout(function() { var oldDomain = domain; // preserve old context domain = trackedDomain; // restore context to "global" variable fn(); // call the function itself domain = oldDomain; // restore old context }, ms); // that it! }; 

Something like express can simply do domain = new RequestContext at the beginning, and then all the methods called in the request will work, since they are all wrapped, as in the example above (since it is again baked in node).

It sounds waved, why remove them?

They are deleted because of the complexity of the implementation that they add, and the fact that they leak, and error recovery has extreme cases when they do not work.

So what should I do?

You have alternatives, for example bluebird promises have .bind , which bring the promise chain context, which is a less-missed way to do this.

However, I would simply avoid the implicit global context. It makes refactoring tough, it makes dependencies implicit, and it makes the code harder to reason about. I just passed the appropriate context to the objects when I create them (nesting in dependencies, in a nutshell), and not setting a global variable.

+4
source

Source: https://habr.com/ru/post/1234085/


All Articles