在node.js中,Windows等效于process.on('SIGINT')是什么?

pap*_*dog 73 windows node.js

我正在按照这里的指导(监听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( )
})
Run Code Online (Sandbox Code Playgroud)

在Windows上,此代码运行,但为时已晚,无法做任何优雅的事情:

process.on( 'exit', function() {
  console.log( "never see this log message" )
})
Run Code Online (Sandbox Code Playgroud)

SIGINTWindows上有同等的事件吗?

Gab*_*mas 137

您必须使用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();
});
Run Code Online (Sandbox Code Playgroud)

  • 这是荒唐的.为什么这不是由节点核心处理的? (32认同)
  • 看起来很久以前就解决了这个问题:https://github.com/nodejs/node-v0.x-archive/issues/5054 (5认同)
  • 因为当你监听stdin时,进程永远不会完成,直到你明确发送一个SIGINT信号. (3认同)
  • 因此,您需要从父级向子级发送随机消息,例如:"SIGINT". (2认同)

Mei*_*hes 15

我不知道什么时候,但在节点8.x和Windows 10上,原始的问题代码现在只能工作.

在此输入图像描述

也适用于Windows命令提示符.


tfm*_*gue 7

除非您需要为其他任务导入"readline",否则我建议在程序验证它在Windows上运行后导入"readline".此外,对于那些可能不知道的人 - 这适用于Windows 32位和Windows 64位系统(将返回关键字"win32").感谢Gabriel这个解决方案.

if (process.platform === "win32") {
  require("readline")
    .createInterface({
      input: process.stdin,
      output: process.stdout
    })
    .on("SIGINT", function () {
      process.emit("SIGINT");
    });
}

process.on("SIGINT", function () {
  // graceful shutdown
  process.exit();
});
Run Code Online (Sandbox Code Playgroud)


Hei*_*cht 6

现在它只适用 于所有平台,包括 Windows。

以下代码记录然后在 Windows 10 上正确终止:

process.on('SIGINT', () => {
    console.log("Terminating...");
    process.exit(0);
});
Run Code Online (Sandbox Code Playgroud)

  • 这在 cygwin 下对我不起作用。使用最新的 Windows 10(自动更新),节点版本 8.11.4。“它不起作用”是指 1) 进程确实终止,但 2) 消息未记录到控制台,3) 创建的 HTTP 连接未关闭。但是,我应该补充一点,我在 PowerShell 下尝试过它,并且在那里按预期工作。但是我改用了 cygwin,因为 PowerShell 有一个错误的 curl 命令。该死! (2认同)
  • 就在今天,它无缘无故地停止了对我的工作(根本没有更新),我仍然不知道为什么。接受的答案修复了它。 (2认同)