Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
     });
});
like image 479
XCS Avatar asked Oct 28 '25 09:10

XCS


2 Answers

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');
     });
});
like image 54
Nivesh Avatar answered Oct 29 '25 23:10

Nivesh


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();
});
like image 39
jmp Avatar answered Oct 29 '25 22:10

jmp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!