node.js 中 process.on('SIGINT') 的 Windows 等效项是什么?

新手上路,请多包涵

我正在按照 此处 的指导(监听 SIGINT 事件)正常关闭我的 Windows-8 托管的 node.js 应用程序以响应 Ctrl + C 或服务器关闭。

但是 Windows 没有 SIGINT 。我也试过 process.on('exit') ,但这似乎晚了做任何有成效的事情。

在 Windows 上,这段代码给了我: 错误:没有这样的模块

process.on( 'SIGINT', function() {
  console.log( "\ngracefully shutting down from  SIGINT (Crtl-C)" )
  // wish this worked on Windows
  process.exit( )
})

在 Windows 上,此代码运行,但 为时已晚,无法优雅地执行任何操作

 process.on( 'exit', function() {
  console.log( "never see this log message" )
})

Windows 上是否有 SIGINT 等效事件?

原文由 Q 4 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

您必须使用 readline 模块并监听 SIGINT 事件:

http://nodejs.org/api/readline.html#readline_event_sigint

 if (process.platform === "win32") {
  var rl = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.on("SIGINT", function () {
    process.emit("SIGINT");
  });
}

process.on("SIGINT", function () {
  //graceful shutdown
  process.exit();
});

原文由 Gabriel Llamas 发布,翻译遵循 CC BY-SA 3.0 许可协议

我不确定何时,但在节点 8.x 和 Windows 10 上,原始问题代码现在可以正常工作。

 process.on( "SIGINT", function() {
  console.log( "\ngracefully shutting down from SIGINT (Crtl-C)" );
  process.exit();
} );

process.on( "exit", function() {
  console.log( "never see this log message" );
} );

setInterval( () => console.log( "tick" ), 2500 );

在此处输入图像描述

也适用于 Windows 命令提示符。

原文由 Meirion Hughes 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题