{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"domain","path":"/domain","type":"module","module":"domain","title":"Domain","introducedIn":"v0.10.0","sourceLink":{"path":"lib/domain.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/domain.js"},"stability":{"index":"0","description":"Deprecated"},"added":[],"deprecated":["v1.4.2"],"removed":[],"napiVersion":[],"changes":[{"versions":["v8.8.0"],"prUrl":"https://github.com/nodejs/node/pull/15695","commit":null,"description":"Any `Promise`s created in VM contexts no longer have a `.domain` property. Their handlers are still executed in the proper domain, however, and `Promise`s created in the main context still possess a `.domain` property."},{"versions":["v8.0.0"],"prUrl":"https://github.com/nodejs/node/pull/12489","commit":null,"description":"Handlers for `Promise`s are now invoked in the domain in which the first promise of a chain was created."}],"description":"**This module is pending deprecation.** Once a replacement API has been\nfinalized, this module will be fully deprecated. Most developers should\n**not** have cause to use this module. Users who absolutely must have\nthe functionality that domains provide may rely on it for the time being\nbut should expect to have to migrate to a different solution\nin the future.\n\nDomains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an `'error'` event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\n`process.on('uncaughtException')` handler, or causing the program to\nexit immediately with an error code.","summary":"**This module is pending deprecation.** Once a replacement API has been finalized, this module will be fully deprecated. Most developers should **not** have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.","examples":[],"children":[{"kind":"section","id":"warning-dont-ignore-errors","name":"Warning: Don't ignore errors!","title":"Warning: Don't ignore errors!","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Domain error handlers are not a substitute for closing down a\nprocess when an error occurs.\n\nBy the very nature of how [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) works in JavaScript, there is almost\nnever any way to safely \"pick up where it left off\", without leaking\nreferences, or creating some other sort of undefined brittle state.\n\nThe safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, there may be many\nopen connections, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.\n\nThe better approach is to send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.\n\nIn this way, `domain` usage goes hand-in-hand with the cluster module,\nsince the primary process can fork a new worker when a worker\nencounters an error. For Node.js programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.\n\nFor example, this is not a good idea:\n\n```js\n// XXX WARNING! BAD IDEA!\n\nconst d = require('node:domain').create();\nd.on('error', (er) => {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // a lot of resources if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log(`error, but oh well ${er.message}`);\n});\nd.run(() => {\n  require('node:http').createServer((req, res) => {\n    handleRequest(req, res);\n  }).listen(PORT);\n});\n```\n\nBy using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.\n\n```js\n// Much better!\n\nconst cluster = require('node:cluster');\nconst PORT = +process.env.PORT || 1337;\n\nif (cluster.isPrimary) {\n  // A more realistic scenario would have more than 2 workers,\n  // and perhaps not put the primary and worker in the same file.\n  //\n  // It is also possible to get a bit fancier about logging, and\n  // implement whatever custom logic is needed to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the primary does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', (worker) => {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  const domain = require('node:domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests. How it works, caveats, etc.\n\n  const server = require('node:http').createServer((req, res) => {\n    const d = domain.create();\n    d.on('error', (er) => {\n      console.error(`error ${er.stack}`);\n\n      // We're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now! Be very careful!\n\n      try {\n        // Make sure we close down within 30 seconds\n        const killtimer = setTimeout(() => {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // Stop taking new requests.\n        server.close();\n\n        // Let the primary know we're dead. This will trigger a\n        // 'disconnect' in the cluster primary, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // Try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // Oh well, not much we can do at this point.\n        console.error(`Error sending 500! ${er2.stack}`);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(() => {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part is not important. Just an example routing thing.\n// Put fancy application logic here.\nfunction handleRequest(req, res) {\n  switch (req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(() => {\n        // Whoops!\n        flerb.bark();\n      }, timeout);\n      break;\n    default:\n      res.end('ok');\n  }\n}\n```","summary":"Domain error handlers are not a substitute for closing down a process when an error occurs.","examples":[{"language":"js","displayName":null,"code":"// XXX WARNING! BAD IDEA!\n\nconst d = require('node:domain').create();\nd.on('error', (er) => {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // a lot of resources if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log(`error, but oh well ${er.message}`);\n});\nd.run(() => {\n  require('node:http').createServer((req, res) => {\n    handleRequest(req, res);\n  }).listen(PORT);\n});"},{"language":"js","displayName":null,"code":"// Much better!\n\nconst cluster = require('node:cluster');\nconst PORT = +process.env.PORT || 1337;\n\nif (cluster.isPrimary) {\n  // A more realistic scenario would have more than 2 workers,\n  // and perhaps not put the primary and worker in the same file.\n  //\n  // It is also possible to get a bit fancier about logging, and\n  // implement whatever custom logic is needed to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the primary does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', (worker) => {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  const domain = require('node:domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests. How it works, caveats, etc.\n\n  const server = require('node:http').createServer((req, res) => {\n    const d = domain.create();\n    d.on('error', (er) => {\n      console.error(`error ${er.stack}`);\n\n      // We're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now! Be very careful!\n\n      try {\n        // Make sure we close down within 30 seconds\n        const killtimer = setTimeout(() => {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // Stop taking new requests.\n        server.close();\n\n        // Let the primary know we're dead. This will trigger a\n        // 'disconnect' in the cluster primary, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // Try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // Oh well, not much we can do at this point.\n        console.error(`Error sending 500! ${er2.stack}`);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(() => {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part is not important. Just an example routing thing.\n// Put fancy application logic here.\nfunction handleRequest(req, res) {\n  switch (req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(() => {\n        // Whoops!\n        flerb.bark();\n      }, timeout);\n      break;\n    default:\n      res.end('ok');\n  }\n}"}],"children":[]},{"kind":"section","id":"additions-to-error-objects","name":"Additions to Error objects","title":"Additions to `Error` objects","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Any time an `Error` object is routed through a domain, a few extra fields\nare added to it.\n\n* `error.domain` The domain that first handled the error.\n* `error.domainEmitter` The event emitter that emitted an `'error'` event\n  with the error object.\n* `error.domainBound` The callback function which was bound to the\n  domain, and passed an error as its first argument.\n* `error.domainThrown` A boolean indicating whether the error was\n  thrown, emitted, or passed to a bound callback function.","summary":"Any time an `Error` object is routed through a domain, a few extra fields are added to it.","examples":[],"children":[]},{"kind":"section","id":"implicit-binding","name":"Implicit binding","title":"Implicit binding","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"If domains are in use, then all **new** `EventEmitter` objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\nAdditionally, callbacks passed to low-level event loop requests (such as\nto `fs.open()`, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\nIn order to prevent excessive memory usage, `Domain` objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\nTo nest `Domain` objects as children of a parent `Domain` they must be\nexplicitly added.\n\nImplicit binding routes thrown errors and `'error'` events to the\n`Domain`'s `'error'` event, but does not register the `EventEmitter` on the\n`Domain`.\nImplicit binding only takes care of thrown errors and `'error'` events.","summary":"If domains are in use, then all **new** `EventEmitter` objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation.","examples":[],"children":[]},{"kind":"section","id":"explicit-binding","name":"Explicit binding","title":"Explicit binding","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\nFor example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\nThat is possible via explicit binding.\n\n```js\n// Create a top-level domain for the server\nconst domain = require('node:domain');\nconst http = require('node:http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n  // Server is created in the scope of serverDomain\n  http.createServer((req, res) => {\n    // Req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    const reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', (er) => {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er2) {\n        console.error('Error sending 500', er2, req.url);\n      }\n    });\n  }).listen(1337);\n});\n```","summary":"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.","examples":[{"language":"js","displayName":null,"code":"// Create a top-level domain for the server\nconst domain = require('node:domain');\nconst http = require('node:http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n  // Server is created in the scope of serverDomain\n  http.createServer((req, res) => {\n    // Req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    const reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', (er) => {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er2) {\n        console.error('Error sending 500', er2, req.url);\n      }\n    });\n  }).listen(1337);\n});"}],"children":[]},{"kind":"method","id":"domaincreate","name":"create","title":"`domain.create()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Domain","links":[{"name":"Domain","href":"domain.html#class-domain","start":0,"end":6}]},"description":""}},"description":"","summary":"","examples":[],"children":[]},{"kind":"class","id":"class-domain","name":"Domain","title":"Class: `Domain`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":{"text":"EventEmitter","links":[{"name":"EventEmitter","href":"events.html#class-eventemitter","start":0,"end":12}]},"description":"The `Domain` class encapsulates the functionality of routing errors and\nuncaught exceptions to the active `Domain` object.\n\nTo handle the errors that it catches, listen to its `'error'` event.","summary":"The `Domain` class encapsulates the functionality of routing errors and uncaught exceptions to the active `Domain` object.","examples":[],"children":[{"kind":"property","id":"domainmembers","name":"members","title":"`domain.members`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Array","links":[{"name":"Array","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array","start":0,"end":5}]},"default":null,"description":"An array of event emitters that have been explicitly added to the domain.","summary":"An array of event emitters that have been explicitly added to the domain.","examples":[],"children":[]},{"kind":"method","id":"domainaddemitter","name":"add","title":"`domain.add(emitter)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v9.3.0"],"prUrl":"https://github.com/nodejs/node/pull/16222","commit":null,"description":"No longer accepts timer objects."}],"signature":{"parameters":[{"name":"emitter","type":{"text":"EventEmitter","links":[{"name":"EventEmitter","href":"events.html#class-eventemitter","start":0,"end":12}]},"description":"emitter to be added to the domain","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an `'error'` event, it\nwill be routed to the domain's `'error'` event, just like with implicit\nbinding.\n\nIf the `EventEmitter` was already bound to a domain, it is removed from that\none, and bound to this one instead.","summary":"Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an `'error'` event, it will be routed to the domain's `'error'` event, just like with implicit binding.","examples":[],"children":[]},{"kind":"method","id":"domainbindcallback","name":"bind","title":"`domain.bind(callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The callback function","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The bound function"}},"description":"The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's `'error'` event.\n\n```js\nconst d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind((er, data) => {\n    // If this throws, it will also be passed to the domain.\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n```","summary":"The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's `'error'` event.","examples":[{"language":"js","displayName":null,"code":"const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind((er, data) => {\n    // If this throws, it will also be passed to the domain.\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});"}],"children":[]},{"kind":"method","id":"domainenter","name":"enter","title":"`domain.enter()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"The `enter()` method is plumbing used by the `run()`, `bind()`, and\n`intercept()` methods to set the active domain. It sets `domain.active` and\n`process.domain` to the domain, and implicitly pushes the domain onto the domain\nstack managed by the domain module (see [`domain.exit()`](#domainexit) for details on the\ndomain stack). The call to `enter()` delimits the beginning of a chain of\nasynchronous calls and I/O operations bound to a domain.\n\nCalling `enter()` changes only the active domain, and does not alter the domain\nitself. `enter()` and `exit()` can be called an arbitrary number of times on a\nsingle domain.","summary":"The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see `domain.exit()` for details on the domain stack). The call to `enter()` delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.","examples":[],"children":[]},{"kind":"method","id":"domainexit","name":"exit","title":"`domain.exit()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"The `exit()` method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to `exit()` delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.\n\nIf there are multiple, nested domains bound to the current execution context,\n`exit()` will exit any domains nested within this domain.\n\nCalling `exit()` changes only the active domain, and does not alter the domain\nitself. `enter()` and `exit()` can be called an arbitrary number of times on a\nsingle domain.","summary":"The `exit()` method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to `exit()` delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.","examples":[],"children":[]},{"kind":"method","id":"domaininterceptcallback","name":"intercept","title":"`domain.intercept(callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The callback function","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The intercepted function"}},"description":"This method is almost identical to [`domain.bind(callback)`](#domainbindcallback). However, in\naddition to catching thrown errors, it will also intercept [`Error`](errors.html#class-error)\nobjects sent as the first argument to the function.\n\nIn this way, the common `if (err) return callback(err);` pattern can be replaced\nwith a single error handler in a single place.\n\n```js\nconst d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept((data) => {\n    // Note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // If this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n```","summary":"This method is almost identical to `domain.bind(callback)`. However, in addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.","examples":[{"language":"js","displayName":null,"code":"const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept((data) => {\n    // Note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // If this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});"}],"children":[]},{"kind":"method","id":"domainremoveemitter","name":"remove","title":"`domain.remove(emitter)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"emitter","type":{"text":"EventEmitter","links":[{"name":"EventEmitter","href":"events.html#class-eventemitter","start":0,"end":12}]},"description":"emitter to be removed from the domain","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The opposite of [`domain.add(emitter)`](#domainaddemitter). Removes domain handling from the\nspecified emitter.","summary":"The opposite of `domain.add(emitter)`. Removes domain handling from the specified emitter.","examples":[],"children":[]},{"kind":"method","id":"domainrunfn-args","name":"run","title":"`domain.run(fn[, ...args])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"args","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"","default":null,"optional":true,"rest":true,"properties":[]}],"returns":null},"description":"Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and low-level requests that are\ncreated in that context. Optionally, arguments can be passed to\nthe function.\n\nThis is the most basic way to use a domain.\n\n```js\nconst domain = require('node:domain');\nconst fs = require('node:fs');\nconst d = domain.create();\nd.on('error', (er) => {\n  console.error('Caught error!', er);\n});\nd.run(() => {\n  process.nextTick(() => {\n    setTimeout(() => { // Simulating some various async stuff\n      fs.open('non-existent file', 'r', (er, fd) => {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});\n```\n\nIn this example, the `d.on('error')` handler will be triggered, rather\nthan crashing the program.","summary":"Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and low-level requests that are created in that context. Optionally, arguments can be passed to the function.","examples":[{"language":"js","displayName":null,"code":"const domain = require('node:domain');\nconst fs = require('node:fs');\nconst d = domain.create();\nd.on('error', (er) => {\n  console.error('Caught error!', er);\n});\nd.run(() => {\n  process.nextTick(() => {\n    setTimeout(() => { // Simulating some various async stuff\n      fs.open('non-existent file', 'r', (er, fd) => {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});"}],"children":[]}]},{"kind":"section","id":"domains-and-promises","name":"Domains and promises","title":"Domains and promises","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"As of Node.js 8.0.0, the handlers of promises are run inside the domain in\nwhich the call to `.then()` or `.catch()` itself was made:\n\n```js\nconst d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then((v) => {\n    // running in d2\n  });\n});\n```\n\nA callback may be bound to a specific domain using [`domain.bind(callback)`](#domainbindcallback):\n\n```js\nconst d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then(p.domain.bind((v) => {\n    // running in d1\n  }));\n});\n```\n\nDomains will not interfere with the error handling mechanisms for\npromises. In other words, no `'error'` event will be emitted for unhandled\n`Promise` rejections.","summary":"As of Node.js 8.0.0, the handlers of promises are run inside the domain in which the call to `.then()` or `.catch()` itself was made:","examples":[{"language":"js","displayName":null,"code":"const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then((v) => {\n    // running in d2\n  });\n});"},{"language":"js","displayName":null,"code":"const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then(p.domain.bind((v) => {\n    // running in d1\n  }));\n});"}],"children":[]}]}