显式绑定


¥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);
});