【问题标题】:Nodemon execute function before every restart每次重启前Nodemon执行功能
【发布时间】:2022-02-05 01:55:25
【问题描述】:

我有一个Node.js 游戏服务器,我通过运行nodemon app.js 来启动它。现在,每次我编辑文件时,服务器都会重新启动。我已经实现了saveload 功能,并且我希望每次游戏服务器重新启动(由于文件更改)时在重新启动之前保存游戏,以便我可以load 重新启动后的先前状态。

我想要的是这样的:

process.on('restart', function(doneCallback) {
   saveGame(doneCallback);
   // The save game is async because it is writing toa file
}

我曾尝试使用SIGUR2 事件,但它从未被触发。这是我尝试过的,但从未调用过该函数。

// Save game before restarting
process.once('SIGUSR2', function () {
     console.log('SIGUR2');
     game.saveGame(function() {
        process.kill(process.pid, 'SIGUSR2');
     });
});

【问题讨论】:

  • 你试过github.com/remy/nodemon/blob/master/doc/events.mdnodemon.on('restart',...)吗?
  • @migg 不,没有包含nodemon 包,将看看。
  • @migg 不,没有调用该事件。
  • 再一次,我从控制台命令启动 nodemon。
  • @AnandUndavia 我不记得了,我想我没有设法让它在 Windows 上工作,我所做的只是定期保存/快照,如果服务器失败/restarted 我只会加载最新的可用 snapshopt。

标签: javascript node.js signals nodemon


【解决方案1】:

以下代码在 Unix 机器上正常工作。现在,由于您的 saveGame 是异步的,您必须从回调中调用 process.kill。

process.once('SIGUSR2', function() {
    setTimeout(()=>{
        console.log('Shutting Down!');
        process.kill(process.pid, 'SIGUSR2');
    },3000);

});

因此,只要您从 game.saveGame() 函数中执行回调函数,您的代码看起来就很好。

// Save game before restarting
process.once('SIGUSR2', function () {
     console.log('SIGUR2');
     game.saveGame(function() {
        process.kill(process.pid, 'SIGUSR2');
     });
});

【讨论】:

  • 这仍然没有回答我的问题,你所说的只是我的代码工作正常,但在我的情况下它不是(在 Windows 上)。
【解决方案2】:

在 Windows 上

像这样运行应用程序:

nodemon --signal SIGINT app.js

在 app.js 中添加代码

let process = require('process');

process.once('SIGINT', function () {
  console.log('SIGINT received');
  your_func();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多