{"_id":"grace","_rev":"41-853e9b8b051144d56cbe00624a3c354d","name":"grace","description":"Graceful application with domains, cluster, error handling and Express support","dist-tags":{"latest":"0.2.5"},"versions":{"0.1.4":{"name":"grace","version":"0.1.4","description":"Graceful shutdown/restart with domains and cluster support","keywords":["graceful","shutdown","restart","domain"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows and Linux and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful shutdown/restart with domains and cluster support ####\n\nVersion: 0.1.4\n\nProvides an event-based mechanism to start and gracefully shutdown a Node.js process when a SIGINT signal is sent to it. Because Windows doesn't have POSIX signals a different method has to be used (reading the stdin for a ctrl-c key). The process can be gracefully killed pressing ctrl-c (Windows & Linux) and sending to it a SIGINT signal (Linux). It also uses domains so uncaught exceptions doesn't kill the process. Furthermore, if you use workers, the shutdown task takes care about that and transparently manages them in order to always guarantee a graceful shutdown providing to the user a last opportunity to clean up tasks asynchronously.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install graceful-shut\n```\n\n#### Example ####\n\n```javascript\nvar gs = require (\"graceful-shut\");\n\nvar app = gs.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed to finish the process but the shutdown\n\t//listener won't be called. Therefore, if you want to always call the shutdown\n\t//listener, always call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\t//The callback must be always called \n\tconsole.error (\"forced shutdown!\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-GracefulShut/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with clusters-. Once you feel comfortable with it you probably will never stop using it.\n\n- [gs.create()](#create)\n- [Grace#dom()](#dom)\n- [Grace#redirectError(error)](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom()__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError(error)__  \nRedirects the error to the `error` event listener.\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending events in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener is not called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\". The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event. The only exceptions that can kill the process  when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server. These errors are not considered \"pure uncaught exceptions\", they're produced during the server initialization. Therefore, uncaught exceptions thrown by a user request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and there won't be any way to finish the process, you'll need to send a SIGINT signal or press ctrl-c. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the exit has been forced. The callback receives a function that must be executed to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the on completion callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside this listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something in console. The exit code is passed as a parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to finalize. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks are done, call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 2 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n\nIs also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event and the \"graceful application\" will be informed about this in order to correctly manage the remaining workers.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.","readmeFilename":"README.md","_id":"grace@0.1.4","dist":{"shasum":"431583a03be47a909f5cbb8c1cdc269e845d2254","tarball":"https://registry.npmjs.org/grace/-/grace-0.1.4.tgz","integrity":"sha512-cd2BH1lrFlOjar98ZrDr5R8E1zWBDeP5Xgt4M8Nnzlmw/hFdcU83Bo813qWJB5zdCkNtspquKsnd4kzBNzO9Wg==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD2WIZLfdyXEcuEsoS5AECugPRGGyuBIjZDMWyK7EAriAIhAIxTFLCCZ4wrpDKhrUZmiay7EMJQ81JvK+0v46NGjqdq"}]},"_from":".","_npmVersion":"1.2.11","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.1.5":{"name":"grace","version":"0.1.5","description":"Graceful shutdown/restart with domains and cluster support","keywords":["graceful","shutdown","restart","domain"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows and Linux and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful shutdown/restart with domains and cluster support ####\n\nVersion: 0.1.5\n\nProvides an event-based mechanism to start and gracefully shutdown a Node.js process when a SIGINT signal is sent to it. Because Windows doesn't have POSIX signals a different method has to be used (reading the stdin for a ctrl-c key). The process can be gracefully killed pressing ctrl-c (Windows & Linux) and sending to it a SIGINT signal (Linux). It also uses domains so uncaught exceptions doesn't kill the process. Furthermore, if you use workers, the shutdown task takes care about that and transparently manages them in order to always guarantee a graceful shutdown providing to the user a last opportunity to clean up tasks asynchronously.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install graceful-shut\n```\n\n#### Example ####\n\n```javascript\nvar gs = require (\"graceful-shut\");\n\nvar app = gs.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed to finish the process but the shutdown\n\t//listener won't be called. Therefore, if you want to always call the shutdown\n\t//listener, always call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\t//The callback must be always called \n\tconsole.error (\"forced shutdown!\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-GracefulShut/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with clusters-. Once you feel comfortable with it you probably will never stop using it.\n\n- [gs.create()](#create)\n- [Grace#dom()](#dom)\n- [Grace#redirectError(error)](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom()__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError(error)__  \nRedirects the error to the `error` event listener.\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending events in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener is not called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\". The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event. The only exceptions that can kill the process  when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server. These errors are not considered \"pure uncaught exceptions\", they're produced during the server initialization. Therefore, uncaught exceptions thrown by a user request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and there won't be any way to finish the process, you'll need to send a SIGINT signal or press ctrl-c. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the exit has been forced. The callback receives a function that must be executed to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the on completion callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside this listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something in console. The exit code is passed as a parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to finalize. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks are done, call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired in the master automatically.\n\nIs also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event and the \"graceful application\" will be informed about this in order to correctly manage the remaining workers.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.","readmeFilename":"README.md","_id":"grace@0.1.5","dist":{"shasum":"ef0fa7abd9054d76cf2aea12dbd20e9eaf23a499","tarball":"https://registry.npmjs.org/grace/-/grace-0.1.5.tgz","integrity":"sha512-YpZ4dWJfLHOnvWcRD9ay+V3tU5J2/5VXKFV2BDdqUtFHCaTAgtun/dRQzGMyuabg7zQ3UekBf6PMGfdH757lMA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIE0Z5IpsoRthrZmCGY2NxlBjnEFXqtgYLD2uOnD6o87tAiEA0vV68dveLcAogjyU7P/9+gpst1i4TQL6bss7CVHk9Eo="}]},"_from":".","_npmVersion":"1.2.11","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.2.0":{"name":"grace","version":"0.2.0","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.0\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nThe Express web framework is fully supported. It can also be used without Express but it's not recommended.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-GracefulShut/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error, request, response])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain.\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error, request, response])__  \nUsed with Express in its error handler. Redirects the error to the request error handler and falls back to the default error handler. The Express error handler should the last middleware.\n\nThere are 2 ways to redirect the Express error:\n\n```javascript\n//Shorthand\nex.use (g.redirectError ());\n\n//If you need to do anything before redirecting\nex.use (function (error, req, res, next){\n\tg.redirectError (error, req, res);\n});\n```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.","readmeFilename":"README.md","_id":"grace@0.2.0","dist":{"shasum":"b257541e77935157b751edca68fd8a1617de0af2","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.0.tgz","integrity":"sha512-irHBUyDcVrvD79/uRbL17qFIkUPOgOpfY1y3ur7LLE8jXBJh2nApRL/WDCQWlnu0m2N7IUuxseyRQz9Er3H4YQ==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCiNXbc6qISQw3KihuREhaOX7wxHbMwuUjb3jIwB1bkZQIgLNeR6NIWad6iGYvpjAmmM5cP+ovQU/AU+sFEbjUjhGs="}]},"_from":".","_npmVersion":"1.2.11","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.2.1":{"name":"grace","version":"0.2.1","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.1\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nThe Express web framework is fully supported. It can also be used without Express but it's not recommended.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-GracefulShut/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error, request, response])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain, otherwise it returns `null`.\n\nIf you are initializing the server (running the code before the http server starts listening a socket) you can use `dom().intercept()` to redirect errors to the default error handler. If you are serving a request you can redirect to the request error handler with `dom(req).intercept()`. If you don't call to `preventDefault` inside the request error handler, the error is redirected automatically to the default error handler, therefore you can have a single point where all the errors are redirected, the default error handler:\n\n```javascript\napp.on (\"error\", function (error){\n\t//This is the only place where you can log fatal errors\n\tlog.fatal (error);\n});\n```\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error, request, response])__  \nUsed with Express in its error handler. Redirects the error to the request error handler and falls back to the default error handler. The Express error handler should the last middleware.\n\nThere are 2 ways to redirect the Express error:\n\n```javascript\n//Shorthand\nex.use (g.redirectError ());\n\n//If you need to do anything before redirecting\nex.use (function (error, req, res, next){\n\tg.redirectError (error, req, res);\n});\n```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.","readmeFilename":"README.md","_id":"grace@0.2.1","dist":{"shasum":"33c2b86f75b4cab3f984410f89a06c6be3fd4c86","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.1.tgz","integrity":"sha512-uPCvXQVOvlvC+kzG86upGx86um3ri/WnEHuSO5gDJALcbptOxDC7pLzPKqy9gq357ykSqStgXMIGSJ2B7UK6Ww==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC7oZ5cGCelXgwS8zVrKV64feBaAmxVg7fpFPkqAW6iHgIgaffw3cxSEbemI+dUb5IH1Fu+8JebvQxut+QQKWkqtp0="}]},"_from":".","_npmVersion":"1.2.11","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.2.2":{"name":"grace","version":"0.2.2","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.2\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nThe Express web framework is fully supported. It can also be used without Express but it's not recommended.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-Grace/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error[, request, response]])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain, otherwise it returns `null`.\n\nIf you are initializing the server (running the code before the http server starts listening a socket) you can use `dom().intercept()` to redirect errors to the default error handler. If you are serving a request you can redirect to the request error handler with `dom(req).intercept()`. If you don't call to `preventDefault` inside the request error handler, the error is redirected automatically to the default error handler, therefore you can have a single point where all the errors are redirected, the default error handler:\n\n```javascript\napp.on (\"error\", function (error){\n\t//This is the only place where you can log fatal errors\n\tlog.fatal (error);\n});\n```\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error[, request, response]])__  \nRedirects an error to an error handler. It redirects to the default or request error handler depending on the number of parameters.\n\n- 0 parameters.  \n  Express -or any frameworks express-like- is required. It's a shorthand to use the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (g.redirectError ());\n  ```\n\n- 1 parameter: error.  \n  Redirects to the default error handler. Useful when you need to do something before redirecting to the default error handler.\n\n\t```javascript\n\t//This redirects errors to the default error handler but you can't do anything before redirecting\n\tasyncFUnction (g.dom ().intercept ());\n\t\n\t//Solution, use redirectError()\n\tasyncFunction (function (error){\n\t\tdoSomething ();\n\t\tg.redirectError (error);\n\t});\n\t```\n\t\n- 3 parameters: error, request, response.  \n  Redirects to the request error handler and falls back to the default error handler if `preventDefault()` is not called. Useful when you need to do something before redirecting to the request error handler. It can be used inside the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (function (error, req, res, next){\n\t\tg.redirectError (error, req, res);\n\t});\n  ```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.\n","readmeFilename":"README.md","_id":"grace@0.2.2","dist":{"shasum":"cc198fcbceee0be66cf892d32a48cfd838846a78","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.2.tgz","integrity":"sha512-5FaCRHtTWZWKMrHgkdt3NINmV7ryfvw8OXV8fuicZSvYCkq2UF+4873GO/IycoZy0ABYk/KgVuWDLI4aY+bmzA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDklqaDCDtOOsihID2l1fZgzoeAMDuVNPzRLlzIZnTYWgIgHLmutc+rd+qeexef8p0BZeEnrDrO+RhJebpzcLciC/g="}]},"_from":".","_npmVersion":"1.2.14","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.2.3":{"name":"grace","version":"0.2.3","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.3\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nThe Express web framework is fully supported. It can also be used without Express but it's not recommended.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-Grace/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error[, request, response]])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain, otherwise it returns `null`.\n\nIf you are initializing the server (running the code before the http server starts listening a socket) you can use `dom().intercept()` to redirect errors to the default error handler. If you are serving a request you can redirect to the request error handler with `dom(req).intercept()`. If you don't call to `preventDefault` inside the request error handler, the error is redirected automatically to the default error handler, therefore you can have a single point where all the errors are redirected, the default error handler:\n\n```javascript\napp.on (\"error\", function (error){\n\t//This is the only place where you can log fatal errors\n\tlog.fatal (error);\n});\n```\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error[, request, response]])__  \nRedirects an error to an error handler. It redirects to the default or request error handler depending on the number of parameters.\n\n- 0 parameters.  \n  Express -or any frameworks express-like- is required. It's a shorthand to use the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (g.redirectError ());\n  ```\n\n- 1 parameter: error.  \n  Redirects to the default error handler. Useful when you need to do something before redirecting to the default error handler.\n\n\t```javascript\n\t//This redirects errors to the default error handler but you can't do anything before redirecting\n\tasyncFUnction (g.dom ().intercept ());\n\t\n\t//Solution, use redirectError()\n\tasyncFunction (function (error){\n\t\tdoSomething ();\n\t\tg.redirectError (error);\n\t});\n\t```\n\t\n- 3 parameters: error, request, response.  \n  Redirects to the request error handler and falls back to the default error handler if `preventDefault()` is not called. Useful when you need to do something before redirecting to the request error handler. It can be used inside the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (function (error, req, res, next){\n\t\tg.redirectError (error, req, res);\n\t});\n  ```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.\n","readmeFilename":"README.md","_id":"grace@0.2.3","dist":{"shasum":"5ab59107842127d108ca14064e502be26d66808b","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.3.tgz","integrity":"sha512-tcaa1sp5hY9twn90agexhFkAEyUjZv9a0uyEE86WhjS6GpWwWIM0gmUolZucvOl+6OEjm143RJRNIXyXH2ZUdQ==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFrzYFZxs6Z0l1kyrtWTmfUHDVDLWmyXH0DeZhPoD0gxAiEAkTqWpkvYkCNzb5nkAFAKha/IQ5JL8nIQRUmDZArV4bg="}]},"_from":".","_npmVersion":"1.2.14","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}],"directories":{}},"0.2.4":{"name":"grace","version":"0.2.4","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.4\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nSome timers can prevent the exit so all of them are cleared before emitting an `exit` event, the user may have forgotten to clear them.\n\nThe Express web framework -and all the Express-like frameworks- is fully supported.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-Grace/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error[, request, response]])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain, otherwise it returns `null`.\n\nIf you are initializing the server (running the code before the http server starts listening a socket) you can use `dom().intercept()` to redirect errors to the default error handler. If you are serving a request you can redirect to the request error handler with `dom(req).intercept()`. If you don't call to `preventDefault` inside the request error handler, the error is redirected automatically to the default error handler, therefore you can have a single point where all the errors are redirected, the default error handler:\n\n```javascript\napp.on (\"error\", function (error){\n\t//This is the only place where you can log fatal errors\n\tlog.fatal (error);\n});\n```\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error[, request, response]])__  \nRedirects an error to an error handler. It redirects to the default or request error handler depending on the number of parameters.\n\n- 0 parameters.  \n  Express -or any frameworks express-like- is required. It's a shorthand to use the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (g.redirectError ());\n  ```\n\n- 1 parameter: error.  \n  Redirects to the default error handler. Useful when you need to do something before redirecting to the default error handler.\n\n\t```javascript\n\t//This redirects errors to the default error handler but you can't do anything before redirecting\n\tasyncFUnction (g.dom ().intercept ());\n\t\n\t//Solution, use redirectError()\n\tasyncFunction (function (error){\n\t\tdoSomething ();\n\t\tg.redirectError (error);\n\t});\n\t```\n\t\n- 3 parameters: error, request, response.  \n  Redirects to the request error handler and falls back to the default error handler if `preventDefault()` is not called. Useful when you need to do something before redirecting to the request error handler. It can be used inside the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (function (error, req, res, next){\n\t\tg.redirectError (error, req, res);\n\t});\n  ```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.\n","readmeFilename":"README.md","_id":"grace@0.2.4","dist":{"shasum":"14265632d07b86cf3f3d4a68693e13693c187e2e","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.4.tgz","integrity":"sha512-KjQjwBp8HpGPEG8RmfWQYhDYqEhquWVZoSYNJRciiJIpoWo1JlDpa1uJPdRAllVsL/5wK3EUocxXO4YURYepaA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCBWbek3Gex0oIZS6zLm7pTra7zt8PAMnopx+nM+oQdQgIhAJHZEHBdyYcq+ioqi+mCYG/JoERlxK5+JPis2P+nf7G9"}]},"_from":".","_npmVersion":"1.2.14","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}]},"0.2.5":{"name":"grace","version":"0.2.5","description":"Graceful application with domains, cluster, error handling and Express support","keywords":["graceful","grace","shutdown","restart","domain","error","handler","uncaught","exception","express"],"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"},"engines":{"node":"*"},"dependencies":{"error-provider":"*"},"devDependencies":{"express":"3.1.x"},"licenses":[{"type":"MIT","url":"http://www.opensource.org/licenses/mit-license.html"}],"main":"lib/grace","readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows, Linux and Express and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful application with domains, cluster, error handling and Express support ####\n\nVersion: 0.2.5\n\nProvides an event-based mechanism to start and gracefully shutdown a web server.\n\nWhen a SIGINT signal is sent to it (on Windows the stdin is read for a ctrl-c key). The server can be gracefully killed pressing ctrl-c (Windows and Linux) and sending a SIGINT signal (Linux).\n\nIt also uses domains (global and per request domains), therefore uncaught exceptions doesn't kill the server, absolutely never.\n\nFurthermore, if you use workers, the shutdown task takes care of them and transparently manages them in order to always guarantee a graceful shutdown giving to the user a last opportunity to clean up resources.\n\nSome timers can prevent the exit so all of them are cleared before emitting an `exit` event, the user may have forgotten to clear them.\n\nThe Express web framework -and all the Express-like frameworks- is fully supported.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install grace\n```\n\n#### Example ####\n\n```javascript\nvar grace = require (\"grace\");\n\nvar app = grace.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed but the shutdown listener won't be called.\n\t//Therefore, if you want to always finish gracefully, call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tconsole.log (\"shutting down\");\n\t//Comment this line and the timeout will do its job\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\tconsole.error (\"timed out, forcing shutdown\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-Grace/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with workers and Express-. Once you feel comfortable with it you probably will never stop using it because it provides the base of a robust web server.\n\n- [gs.create()](#create)\n- [Grace#dom([request])](#dom)\n- [Grace#errorHandler([callback])](#errorHandler)\n- [Grace#redirectError([error[, request, response]])](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom([request])__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\nIf no parameters are passed it returns the default domain. If the request is passed it returns the request domain, otherwise it returns `null`.\n\nIf you are initializing the server (running the code before the http server starts listening a socket) you can use `dom().intercept()` to redirect errors to the default error handler. If you are serving a request you can redirect to the request error handler with `dom(req).intercept()`. If you don't call to `preventDefault` inside the request error handler, the error is redirected automatically to the default error handler, therefore you can have a single point where all the errors are redirected, the default error handler:\n\n```javascript\napp.on (\"error\", function (error){\n\t//This is the only place where you can log fatal errors\n\tlog.fatal (error);\n});\n```\n\n<a name=\"errorHandler\"></a>\n__Grace#errorHandler([callback])__  \nUsed with Express. This should be the very first middleware. Its purpose is to create a per request domain. All the errors produced during a request will catched by this middleware. When this happens the callback is called and 4 parameters are passed: the error, request, response and a function named `preventDefault`. By design the request errors are redirected to the default error handler -the listener attached to the `error` event-. If `preventDefault()` is called the request error won't be redirected.\n\nUsually, the request error handler sends a 500 error and the default error handler logs the error with the highest priority. This means that you can have only 1 function in all the web server that logs fatal errors!\n\n```javascript\nex.use (g.errorHandler (function (error, req, res, preventDefault){\n\tres.send (500);\n}));\n```\n\nYou can also use this function without Express to create per request domains but definitely is not the right way to go. See the [server](https://github.com/Gagle/Node-Grace/blob/master/examples/server.js) example.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError([error[, request, response]])__  \nRedirects an error to an error handler. It redirects to the default or request error handler depending on the number of parameters.\n\n- 0 parameters.  \n  Express -or any frameworks express-like- is required. It's a shorthand to use the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (g.redirectError ());\n  ```\n\n- 1 parameter: error.  \n  Redirects to the default error handler. Useful when you need to do something before redirecting to the default error handler.\n\n\t```javascript\n\t//This redirects errors to the default error handler but you can't do anything before redirecting\n\tasyncFUnction (g.dom ().intercept ());\n\t\n\t//Solution, use redirectError()\n\tasyncFunction (function (error){\n\t\tdoSomething ();\n\t\tg.redirectError (error);\n\t});\n\t```\n\t\n- 3 parameters: error, request, response.  \n  Redirects to the request error handler and falls back to the default error handler if `preventDefault()` is not called. Useful when you need to do something before redirecting to the request error handler. It can be used inside the Express error handler.\n\n  ```javascript\n  //Express error handler, last middleware\n  ex.use (function (error, req, res, next){\n\t\tg.redirectError (error, req, res);\n\t});\n  ```\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending callbacks in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener won't be called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\" emitting a `start` event. The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event listener. The only errors that can kill the process when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server and those that occurs inside the `error` event listener. These errors are not considered \"pure uncaught exceptions\". Therefore, uncaught exceptions thrown by a request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit when the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and won't be any way to gracefully finish the process. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the timeout expires, before forcing the exit. The callback receives a function that must be called to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside the listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something to the console. The exit code is passed as parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to shutdown. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks have been done. Call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 3 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n- When all the workers die the `shutdown` event is fired automatically in the master.\n\nIt's also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.\n","readmeFilename":"README.md","_id":"grace@0.2.5","dist":{"shasum":"4259b5946a3e354536e284dc842f09188b192f02","tarball":"https://registry.npmjs.org/grace/-/grace-0.2.5.tgz","integrity":"sha512-m9jRda418aCc7bxNfxcGZUj19k9PrSS33mw8xxCxp9bCICuSkjmofxUxANX51N5K5ZtXaw5q0wr88sZR4bombQ==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQC6+RTU2BIq99GEgMIsZFk514d+rojT/Y7z5gOF1MQO5wIgEuIppH8X9eL2TOQxHsFOXgqboB62aHR0WDVsmmVvCZ4="}]},"_from":".","_npmVersion":"1.2.14","_npmUser":{"name":"Gagle","email":"gaglekas@gmail.com"},"maintainers":[{"name":"Gagle","email":"gaglekas@gmail.com"}]}},"readme":"grace\n=====\n\n_Node.js project_\n\n## Warning\nBecause it's pretty hard to write concurrent code, treat with the master and the workers, overriding source code, supporting Windows and Linux and writing a transparent API, this module is in a beta state until it reaches v1.0.0.\n\nIt's working pretty well with the provided examples and is actively tested in edge cases. If you find a bug, please report it.\n***\n\n#### Graceful shutdown/restart with domains and cluster support ####\n\nVersion: 0.1.4\n\nProvides an event-based mechanism to start and gracefully shutdown a Node.js process when a SIGINT signal is sent to it. Because Windows doesn't have POSIX signals a different method has to be used (reading the stdin for a ctrl-c key). The process can be gracefully killed pressing ctrl-c (Windows & Linux) and sending to it a SIGINT signal (Linux). It also uses domains so uncaught exceptions doesn't kill the process. Furthermore, if you use workers, the shutdown task takes care about that and transparently manages them in order to always guarantee a graceful shutdown providing to the user a last opportunity to clean up tasks asynchronously.\n\nIf the process finishes correctly the exit code is 0, otherwise 1. The process can also exit with a custom code.\n\n#### Installation ####\n\n```\nnpm install graceful-shut\n```\n\n#### Example ####\n\n```javascript\nvar gs = require (\"graceful-shut\");\n\nvar app = gs.create ();\n\napp.on (\"error\", function (error){\n\t//Unhandled and redirected errors\n\tconsole.error (error);\n});\n\napp.on (\"start\", function (){\n\t//On Windows shutdown() must be called in order to call the shutdown listener\n\t//and exit. On Linux is not needed to finish the process but the shutdown\n\t//listener won't be called. Therefore, if you want to always call the shutdown\n\t//listener, always call to shutdown().\n\tapp.shutdown ();\n});\n\napp.on (\"shutdown\", function (cb){\n\t//Clean up tasks\n\tcb ();\n});\n\napp.on (\"exit\", function (code){\n\tconsole.log (\"bye (\" + code + \")\");\n});\n\napp.timeout (1000, function (cb){\n\t//The timeout is used if the shutdown task takes more time than expected\n\t//The callback must be always called \n\tconsole.error (\"forced shutdown!\");\n\tcb ();\n});\n\napp.start ();\n```\n\n#### Methods and Properties ####\n\nTake a look at the [examples](https://github.com/Gagle/Node-GracefulShut/blob/master/examples) to fully understand how to use a \"graceful application\" -especially with clusters-. Once you feel comfortable with it you probably will never stop using it.\n\n- [gs.create()](#create)\n- [Grace#dom()](#dom)\n- [Grace#redirectError(error)](#redirectError)\n- [Grace#shutdown([exitCode])](#shutdown)\n- [Grace#start()](#start)\n- [Grace#timeout(ms[, callback])](#timeout)\n\n<a name=\"create\"></a>\n__gs.create()__  \nCreates a \"graceful application\" that emits `error`, `start` and `shutdown` events. Only one \"graceful application\" can be created per Node.js process.\n\n<a name=\"dom\"></a>\n__Grace#dom()__  \nReturns the domain used internally that is listenig for errors. Useful when you want to use [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback) to redirect errors to the internal domain.\n\n<a name=\"redirectError\"></a>\n__Grace#redirectError(error)__  \nRedirects the error to the `error` event listener.\n\n<a name=\"shutdown\"></a>\n__Grace#shutdown([exitCode])__  \nProgramatically shutdowns the Node.js process. The listener attached to the `shutdown` event will be called before shutting down the process. On Windows this function must be called in order to shutdown the process even if there's no pending events in the event loop queue because the process is continuously reading the stdin. On Linux it's not needed to call it when the event loop is emty because the process automatically finishes, but the shutdown listener is not called, so for compatibility and reusability of the same code on different platforms it's recommended to always call to `shutdown()` both on Windows and Linux when you want exit.\n\nCalling to `process.exit()` will exit your application without calling the shutdown listener. Use it if you want to exit immediately but I recommend to always call to the `shutdown()` function and set a timeout to give an opportunity to gracefully shutdown before forcing the exit. So, if you want to exit, use `Grace#shutdown()` instead of `process.exit()`.\n\nIf you use workers they're managed for you so you don't need to worry if a worker hangs up when shutting down the server (probably by one or more active long living connections), just set a timeout and it will be killed.\n\nThe listener runs inside a domain. Unhandled exceptions will be handled by the `error` event.\n\n<a name=\"start\"></a>\n__Grace#start()__  \nStarts the \"graceful application\". The listener runs inside a domain. Unhandled exceptions will be handled by the `error` event. The only exceptions that can kill the process  when the server is up and listening for new connections are those that are produced synchronously at compile-time when initializing the server. These errors are not considered \"pure uncaught exceptions\", they're produced during the server initialization. Therefore, uncaught exceptions thrown by a user request will never kill the entire server, that's for sure.\n\n<a name=\"timeout\"></a>\n__Grace#timeout(ms[, callback])__  \nAdds a timeout in milliseconds to wait before forcing the exit the shutdown task takes more than expected. By default there's no timeout so the master/workers can hang up and there won't be any way to finish the process, you'll need to send a SIGINT signal or press ctrl-c. It's strongly recommended to always configure a timeout.\n\nAn optional callback can be passed. It will be executed when the exit has been forced. The callback receives a function that must be executed to completely finish the process. This callback it's only for informational purposes like printing to console. It's up to you if you do any asynchronous calls like sending an email to the administrator or whatever, but make sure to <span style=\"text-decoration: underline\">__always__</span> call the on completion callback or the process will never end.\n\n#### Events ####\n\n- [error](#event-error)\n- [exit](#event-exit)\n- [shutdown](#event-shutdown)\n- [start](#event-start)\n\n<a name=\"event-error\"></a>\n__error__  \nEmitted when an unhandled exception has been thrown or has been redirected to the domain with [Domain#intercept()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domaininterceptcallback) or [Domain#bind()](https://github.com/joyent/node/blob/master/doc/api/domain.markdown#domainbindcallback). Exceptions thrown inside this listener will kill the process, be careful.\n\n<a name=\"event-exit\"></a>\n__exit__  \nEmitted when the process is going to die. The event loop doesn't work at this point so asynchronous tasks won't work. Tipically used to print something in console. The exit code is passed as a parameter.\n\n<a name=\"event-shutdown\"></a>\n__shutdown__  \nEmitted when the Node.js process is going to finalize. This is the last chance to gracefully shutdown the process so this is the place to close any open resources like database connections, flush buffered data to disk, etc. A callback is passed to the listener to call it when all the clean up tasks are done, call it or the process will hang up. You can also pass an error to the callback and it will be emitted back again and redirected to the `error` event listener. This event is fired in 2 circumstances:\n\n- Ctrl-c key or SIGINT signal is received. On Windows only the master process can receive a SIGINT (from a ctrl-c). If the master receives a ctrl-c/SIGINT and it uses workers, they will receive a `shutdown` event so they will be automatically finished.\n- `Grace#shutdown()` is called. If it's called on the master and you use workers all of them will receive a `shutdown` event and will be disconnected. If you call to `shutdown()` directly from a worker it will be destroyed.\n\nIs also possible to directly call to `disconnect()` and `destroy()` in a worker. If you call to `disconnect` the `shutdown` event will be fired and if you call to `destroy()` it will be directly killed without firing a `shutdown` event and the \"graceful application\" will be informed about this in order to correctly manage the remaining workers.\n\n<a name=\"event-start\"></a>\n__start__  \nEmitted right after the `start()` function is called.","maintainers":[{"name":"gagle","email":"gabriel_llamas_llopis@yahoo.es"}],"time":{"modified":"2022-06-18T13:45:18.200Z","created":"2013-02-28T18:02:18.236Z","0.1.4":"2013-02-28T18:02:21.802Z","0.1.5":"2013-02-28T20:52:41.851Z","0.2.0":"2013-03-04T19:17:05.405Z","0.2.1":"2013-03-05T14:26:18.604Z","0.2.2":"2013-03-09T15:45:09.616Z","0.2.3":"2013-03-15T18:40:54.225Z","0.2.4":"2013-03-15T23:21:50.690Z","0.2.5":"2013-03-16T11:59:24.132Z"},"author":{"name":"Gabriel Llamas","email":"gaglekas@gmail.com"},"repository":{"type":"git","url":"git://github.com/Gagle/Node-Grace.git"}}