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.

    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.

    1. // Create a top-level domain for the server
    2. const domain = require('domain');
    3. const http = require('http');
    4. const serverDomain = domain.create();
    5. serverDomain.run(() => {
    6. // Server is created in the scope of serverDomain
    7. http.createServer((req, res) => {
    8. // Req and res are also created in the scope of serverDomain
    9. // however, we'd prefer to have a separate domain for each request.
    10. // create it first thing, and add req and res to it.
    11. const reqd = domain.create();
    12. reqd.add(req);
    13. reqd.add(res);
    14. reqd.on('error', (er) => {
    15. console.error('Error', er, req.url);
    16. try {
    17. res.writeHead(500);
    18. res.end('Error occurred, sorry.');
    19. } catch (er2) {
    20. console.error('Error sending 500', er2, req.url);
    21. }
    22. });
    23. }).listen(1337);
    24. });