从代码级别重启node.js应用 [英] Restart a node.js app from code level
问题描述
我有一个应用程序,该应用程序最初创建了static
个配置文件(一次),写入文件后,我需要重新初始化/重新启动该应用程序.
是否可以从自身重新启动 node.js 应用程序?
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?
这是必需的,因为我有一个应用程序在 node.js 中的两个runlevels
中运行.
最初的启动完全synchronus
,完成此级别后,应用程序将在先前启动的环境中处于异步运行级别.
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.
我知道有诸如nodemon之类的工具,但这并不是我需要的.
I know there are tools like nodemon but that's not what I need in my case.
我试图通过正在运行的process.kill()
终止该应用程序,但是我听不到kill事件:
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?
推荐答案
找到了一个可行的案例,以使node.js
从应用程序本身重新启动:
Found a working case to get node.js
restarted from app itself:
示例:
// 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.
这篇关于从代码级别重启node.js应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!