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.
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.