Node 和 NPM 运行脚本和 Ctrl-C 两次触发 SIGINT [英] Node and NPM Running script and Ctrl-C triggers SIGINT twice

查看:172
本文介绍了Node 和 NPM 运行脚本和 Ctrl-C 两次触发 SIGINT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 npm start(它只运行 node app.js)运行的 Nodejs 应用程序之一上遇到了问题.

I've come across a problem on one of my Nodejs apps running with npm start (which just does node app.js).

我的应用程序包含一个 sigint 处理程序,如下所示:

My app contains a sigint handler as follows:

process.on('SIGINT', () => {
    db.disconnect().then({
        process.exit(0);
    }).catch(e => process.exit(1));
});

带有相应的日志.在对其他文件进行了一些测试之后,我注意到在 npm 进程上的 Ctrl-C 会触发 SIGINT 两次,如果第一个需要很长时间退出.(尝试在示例应用上添加超时).

With corresponding logs. After some testing on other files, I've noticed that Ctrl-C when on an npm process triggers SIGINT twice if the first one takes too long to exit. (try adding a timeout on a sample app).

现在我已经添加了一个计数器来检查调用是否多次执行,但我不确定这是关于这个问题的要走的路".我猜测 npm 进程上的 SIGINT 预计会在某个时间范围内退出,这就是 npm 再传递一次(总是只有两次)的原因.

For now I've added a counter to check if the call is performed more than once, but I'm not sure that's "the way to go" concerning this issue. I'm guessing that a SIGINT on an npm process is expected to quit in a certain timeframe, which is why npm passes it on one more time (always only twice).

有没有人遇到过这个问题并找到了可行的解决方案?

Has anyone come across this problem and found a viable solution?

谢谢!

推荐答案

我知道这篇文章已经发布了一段时间,但不幸的是我遇到了同样的问题.当只运行 node 时,它只触发一个信号.如果运行 npm start,该信号会出现两次.取而代之的是计数器,我建议检查服务器是否仍在侦听,如果是,则继续您的逻辑和内部终止(如数据库连接等):

I know this post has been around for a while but unfortunately I'm getting the same issue. When running just node <app.js> it fires just one signal. That signal comes twice if running npm start. Instead a counter, I suggest check if the server is still listening, if yes, proceed with your logic and internal termination (like db connections etc):

process.on('SIGINT', function(){
 if (server.listening) {
    server.close(function (err) {
      if (err) {
        console.error(err);
        process.exit(1)
      }
      process.exit(0);
    })
 }
})

这篇关于Node 和 NPM 运行脚本和 Ctrl-C 两次触发 SIGINT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆