显式绑定


【Explicit binding】

有时,正在使用的域并不是某个特定事件触发器应该使用的域。或者,事件触发器可能是在一个域的上下文中创建的,但本应绑定到另一个域。

【Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain.】

例如,可能有一个域名用于 HTTP 服务器,但我们可能希望为每个请求使用一个单独的域名。

【For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request.】

这可以通过显式绑定来实现。

【That is possible via explicit binding.】

// Create a top-level domain for the server
const domain = require('node:domain');
const http = require('node:http');
const serverDomain = domain.create();

serverDomain.run(() => {
  // Server is created in the scope of serverDomain
  http.createServer((req, res) => {
    // Req and res are also created in the scope of serverDomain
    // however, we'd prefer to have a separate domain for each request.
    // create it first thing, and add req and res to it.
    const reqd = domain.create();
    reqd.add(req);
    reqd.add(res);
    reqd.on('error', (er) => {
      console.error('Error', er, req.url);
      try {
        res.writeHead(500);
        res.end('Error occurred, sorry.');
      } catch (er2) {
        console.error('Error sending 500', er2, req.url);
      }
    });
  }).listen(1337);
});