javascript - 从代码级别重启 node.js 应用程序

标签 javascript node.js sigkill

我有一个最初创建static 配置文件(一次)的应用程序,在写入文件后我需要重新初始化/重启应用程序。 有什么可以从自身重启 node.js 应用程序吗?

这是必需的,因为我有一个应用程序在 node.js 中的两个 runlevels 中运行。 初始的完全启动 synchronus 并且在此级别完成后,应用程序在先前启动的环境中处于异步运行级别。

我知道有像 nodemon 这样的工具,但这不是我所需要的。

我试图通过正在运行的 process.kill() 终止应用程序,但我听不到 kill 事件:

 // 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();

或者有更好、更简洁的方法来处理这个问题吗?

最佳答案

找到一个工作案例,让 node.js 从应用程序本身重新启动:

示例:

// 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();
  });
}

我在这里看到的唯一缺点是在控制台上丢失输出,但如果有任何内容记录到日志文件中,这不是问题。

关于javascript - 从代码级别重启 node.js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24666696/

相关文章:

python - 与 parent 一起杀死 child

我可以使用 pthread_kill 停止(暂停)pthread 执行吗

javascript - 如何让按钮在点击时显示

javascript - 根据值查找最后嵌套 n 次的对象

php - 如何将 facebook 登录响应从 javascript 传递到 php 页面?

javascript - 为什么我无法在Socket.IO中保存当前房间?

java - 从 Node 中杀死 java (Leiningen) 进程

javascript - 除了在每个模型文件中包含 require ('mongoose' ) 之外,还有更好的方法吗?

javascript - Heroku 上传 Node 应用程序和 Java jar

node.js - 在 React/Redux 应用程序的 cookie 中保护 JWT 的最佳方法是什么?