2

I am developing Node.js application using Node-dev. Each time I save the script of the application (press Control-S) node-dev will restart my app. Now the question, can I detect the restart withing the application, so that I can save some data before the program is terminated?

process.on('SIGINT', function() {
   console.log('SIGINT');
});

The code above does not detect this kind of restart.

I am using Windows XP.

exebook
  • 32,014
  • 33
  • 141
  • 226

1 Answers1

4

In your child, add a listener on the exit event of process:

process.on('exit', function() {
  // Save application state
});

As you can see from the source, node-dev forks to launch your script. When one file changes, the parent launches its stop() function, waits for the child to exit and then restarts it:

child.on('exit', start)
stop()

The stop() function sends a message:

ipc.send({exit: true}, child)

The ipc object uses the child.send() method:

if (dest.send) dest.send(m)

node-dev doesn't work by sending a SIGINT signal, but works using IPCs. It would seem that you can then detect the restart of your application by adding a listener on the message event of process... but this doesn't work (ie. the message event is never emitted on the process object). My guess is that process.exit() is synchronous and that our handler doesn't get the chance to run.

Edit: here is a Gist with an example of parent/child communication using IPC in Node, if that helps.

Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
  • Thank you very much for this detailed answer. But it does not work for me. Probably because I am using Windows XP. – exebook Nov 19 '13 at 13:57
  • What isn't working? Do you catch an event? If you do a `console.log(m)` inside the `process.on('message')`, does it output anything? – Paul Mougel Nov 19 '13 at 14:01
  • that's exactly what I was trying to do. no output. I thought that maybe the console handle is invalid and tried to save to file instead, nothing. the process.on('message') does not fire. – exebook Nov 19 '13 at 14:55