Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - Restart a node.js app from code level

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 to restart a node.js app from itself?

This is required cause I've an application running in two runlevels in node.js. The initial one starts completly synchronus and after this level has been completed app is in async runlevel in a previously started environment.

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

I tried to kill the app via process.kill() which is working but I can't 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...