0

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
Sathish
  • 2,056
  • 3
  • 26
  • 40
  • JavaScript has `try`/`catch`, but you really shouldn't be using that for **crash** handling in any language. Check out this question: http://stackoverflow.com/a/7313005/362536 Also, you're probably going to want to do something in the event the kernel kills off your process for some reason (such as running out of memory). In those cases, you must monitor your process externally. – Brad Oct 12 '14 at 19:44

2 Answers2

1

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
Emmett
  • 14,035
  • 12
  • 56
  • 81
  • Hi Emmett, Thanks!!! But that exit is not fired. when i stop the server.Could you please give me sample. I am using express.js & child process also. – Sathish Oct 14 '14 at 06:37
0

When you are using node JS it's bad practice to use try / catch, because of big number of asynchronous calls. The best practice here to use "promises" review next link, there you can find a good explanation: https://www.promisejs.org/

Simcha
  • 3,300
  • 7
  • 29
  • 42