Handling critical events
All apps are susceptible to crashes and signal terminations. Production-ready apps are supposed to handle these critical events as gracefully and usefully as possible when they can, rather than crash abruptly.
In this section, we will learn how to handle fatal errors and termination signals from our app.
Closing the server
One of the first things to do in the event of something critical is to close the server to new connections, so that we can perform the necessary housekeeping before finally terminating the process.
When we start the server using http.createServer()
, the method returns an instance of Node's web server object, which has a method called close()
that will stop the server from receiving new requests.
Note
You can read more about the HTTP Server object at http://nodejs.org/docs/latest/api/http.html#http_http_createserver_requestlistener.
Following is a simple example of using the server's close()
method. This app will respond to the first request it receives...