XCS
XCS

Reputation: 28137

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');
     });
});

Upvotes: 4

Views: 4241

Answers (2)

Mr. Smit
Mr. Smit

Reputation: 2532

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();
});

Upvotes: 1

Nivesh
Nivesh

Reputation: 2603

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');
     });
});

Upvotes: 3

Related Questions