Restart a node.js app from code level

给你一囗甜甜゛ 提交于 2019-11-29 10:50:41

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!