Restart a node.js app from code level

后端 未结 1 866
猫巷女王i
猫巷女王i 2020-12-17 23:49

I\'ve an app which initially creates static config files (once) and after files were written I need to reinitialize/restart the application. Is there something

相关标签:
1条回答
  • 2020-12-18 00:44

    Found a working case to get node.js restarted from app itself:

    Example:

    // Optional part (if there's 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's 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 con I can see here is to loose outputs on console but if anything is logged into logfiles it's not a problem.

    0 讨论(0)
提交回复
热议问题