'Nodemon execute function before every restart

I have a Node.js game server and I start it by running nodemon app.js. Now, every time I edit a file the server restarts. I have implemented save and load functions and I want every time the game server restarts (due to the file chages) the game to be saved before restarting so that I can load the previous state after the restart.

Something like this is what I want:

process.on('restart', function(doneCallback) {
   saveGame(doneCallback);
   // The save game is async because it is writing toa file
}

I have tried using the SIGUR2 event but it was never triggered. This is what I tried, but the function was never called.

// Save game before restarting
process.once('SIGUSR2', function () {
     console.log('SIGUR2');
     game.saveGame(function() {
        process.kill(process.pid, 'SIGUSR2');
     });
});


Solution 1:[1]

Below code works properly in Unix machine. Now, As your saveGame is asynchronous you have to call process.kill from within the callback.

process.once('SIGUSR2', function() {
    setTimeout(()=>{
        console.log('Shutting Down!');
        process.kill(process.pid, 'SIGUSR2');
    },3000);

});

So, your code looks fine as long as you execute your callback function from within the game.saveGame() function.

// Save game before restarting
process.once('SIGUSR2', function () {
     console.log('SIGUR2');
     game.saveGame(function() {
        process.kill(process.pid, 'SIGUSR2');
     });
});

Solution 2:[2]

on Windows

run app like this:

nodemon --signal SIGINT app.js

in app.js add code

let process = require('process');

process.once('SIGINT', function () {
  console.log('SIGINT received');
  your_func();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nivesh
Solution 2 jmp