Search code examples
javascriptnode.jsnode.js-domains

Node.js Server Crash Handling


Is there any way i can do some database updation things whenever my node.js server crashes or stopped. Like try{}catch(){}finally(){} in JAVA. I am a bit newbie here.

Is there any events will node emit before it going shutdown. If so i can write my function there.

I have scenario,if i stop the server manually,i need to update some fields in the database. The same is for Unhandled crashes also.

i here about domain in Node.js. But i have no idea how to monitor a whole server using domain.


Solution

  • An event is emitted when the node process is about to exit:

    process.on('exit', function(code) {
        console.log('About to exit with code:', code);
    });
    

    http://nodejs.org/api/process.html#process_event_exit

    You can't query the database here though, since this handler can only perform synchronous operations. Some possible alternatives:

    • use database transactions so you never need to do "database updation things" when your app crashes
    • use a tool like Upstart to automatically restart your process, and then do database fixup stuff whenever your process starts