{ "source": "doc/api/domain.markdown", "modules": [ { "textRaw": "Domain", "name": "domain", "stability": 2, "stabilityText": "Unstable", "desc": "

Domains 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\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.\n\n

\n", "miscs": [ { "textRaw": "Warning: Don't Ignore Errors!", "name": "Warning: Don't Ignore Errors!", "type": "misc", "desc": "

Domain error handlers are not a substitute for closing down your\nprocess when an error occurs.\n\n

\n

By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely "pick up where you left off", without leaking\nreferences, or creating some other sort of undefined brittle state.\n\n

\n

The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, you might have many\nconnections open, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.\n\n

\n

The better approach is 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\n

\n

In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For node programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.\n\n

\n

For example, this is not a good idea:\n\n

\n
// XXX WARNING!  BAD IDEA!\n\nvar d = require('domain').create();\nd.on('error', function(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  // resources like crazy 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(function() {\n  require('http').createServer(function(req, res) {\n    handleRequest(req, res);\n  }).listen(PORT);\n});
\n

By 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

\n
// Much better!\n\nvar cluster = require('cluster');\nvar PORT = +process.env.PORT || 1337;\n\nif (cluster.isMaster) {\n  // In real life, you'd probably use more than just 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // You can also of course get a bit fancier about logging, and\n  // implement whatever custom logic you need 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 master does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', function(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  var domain = require('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  var server = require('http').createServer(function(req, res) {\n    var d = domain.create();\n    d.on('error', function(er) {\n      console.error('error', er.stack);\n\n      // Note: 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        var killtimer = setTimeout(function() {\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 master know we're dead.  This will trigger a\n        // 'disconnect' in the cluster master, 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(function() {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part isn't important.  Just an example routing thing.\n// You'd put your 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(function() {\n        // Whoops!\n        flerb.bark();\n      });\n      break;\n    default:\n      res.end('ok');\n  }\n}
\n" }, { "textRaw": "Additions to Error objects", "name": "Additions to Error objects", "type": "misc", "desc": "

Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

\n\n" }, { "textRaw": "Implicit Binding", "name": "Implicit Binding", "type": "misc", "desc": "

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\n

\n

Additionally, callbacks passed to lowlevel 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\n

\n

In 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\n

\n

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.\n\n

\n

Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

\n" }, { "textRaw": "Explicit Binding", "name": "Explicit Binding", "type": "misc", "desc": "

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\n

\n

For 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\n

\n

That is possible via explicit binding.\n\n

\n

For example:\n\n

\n
// create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(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    var reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n      }\n    });\n  }).listen(1337);\n});
\n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "return: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

Returns a new Domain object.\n\n

\n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

\n

Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

\n", "methods": [ { "textRaw": "domain.run(fn)", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} ", "name": "fn", "type": "Function" } ] }, { "params": [ { "name": "fn" } ] } ], "desc": "

Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

\n

This is the most basic way to use a domain.\n\n

\n

Example:\n\n

\n
var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
\n

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

\n" }, { "textRaw": "domain.add(emitter)", "type": "method", "name": "add", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be added to the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

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\n

\n

This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

\n

If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

\n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

\n" }, { "textRaw": "domain.bind(callback)", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "return: {Function} The bound function ", "name": "return", "type": "Function", "desc": "The bound function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

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

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(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', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" }, { "textRaw": "domain.intercept(callback)", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "return: {Function} The intercepted function ", "name": "return", "type": "Function", "desc": "The intercepted function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

\n

In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(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', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" }, { "textRaw": "domain.enter()", "type": "method", "name": "enter", "desc": "

The enter method is plumbing used by the run, bind, and intercept\nmethods to set the active domain. It sets domain.active and process.domain\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit() for details on the domain stack). The\ncall to enter delimits the beginning of a chain of asynchronous calls and I/O\noperations bound to a domain.\n\n

\n

Calling 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.\n\n

\n

If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.exit()", "type": "method", "name": "exit", "desc": "

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\n

\n

If there are multiple, nested domains bound to the current execution context,\nexit will exit any domains nested within this domain.\n\n

\n

Calling 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.\n\n

\n

If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.dispose()", "type": "method", "name": "dispose", "desc": "

The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

\n

The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

\n

Once the domain is disposed the dispose event will emit.\n\n

\n

Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`members` {Array} ", "name": "members", "desc": "

An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

\n" } ] } ], "type": "module", "displayName": "Domain" } ] }