Restart the node.js application from the code level

I have an application that initially creates configuration files static(once) and after the files have been written, I need to reinitialize / restart the application. Is there something to restart the node.js application on my own?

This is necessary, because I have an application running in two runlevelsto node.js . The initial completion is completed synchronus, and after this level has been completed, the application is in the asynchronous run level in a previously running environment.

I know there are tools like nodemon, but that is not what I need in my case.

I tried to kill the application through process.kill(), which works, but I can not listen to the kill event:

 // Add the listener
 process.on('exit', function(code) {
    console.log('About to exit with code:', code);
    // Start app again but how?
 });

 // Kill application
 process.kill();

Or is there a better, cleaner way to handle this?

+4
source share
1 answer

Found a working example to get node.jsrestartable from the application itself:

Example:

// Optional part (if there an running webserver which blocks a port required for next startup
try {
  APP.webserver.close(); // Express.js instance
  APP.logger("Webserver was halted", 'success');
} catch (e) {
  APP.logger("Cant't stop webserver:", 'error'); // No server started
  APP.logger(e, 'error');
}


// First I create an exec command which is executed before current process is killed
var cmd = "node " + APP.config.settings.ROOT_DIR + 'app.js';

// Then I look if there already something ele killing the process  
if (APP.killed === undefined) {
  APP.killed = true;

  // Then I excute the command and kill the app if starting was successful
  var exec = require('child_process').exec;
  exec(cmd, function () {
    APP.logger('APPLICATION RESTARTED', 'success');
    process.kill();
  });
}

The only thing I see here is to lose the output on the console, but if something is written to the log files, this is not a problem.

+7
source

Source: https://habr.com/ru/post/1547851/


All Articles