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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10021373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:27:17  来源:igfitidea点击:

What is the Windows equivalent of process.on('SIGINT') in node.js?

windowsnode.js

提问by pappadog

I'm following the guidance here(listening for SIGINTevents) to gracefully shutdown my Windows-8-hosted node.js application in response to Ctrl+Cor server shutdown.

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

But Windows doesn't have SIGINT. I also tried process.on('exit'), but that seems to late to do anything productive.

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

On Windows, this code gives me: Error: No such module

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

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

On Windows, this code runs, but is too late to do anything graceful:

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

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

Is there a SIGINTequivalent event on Windows?

SIGINTWindows 上是否有等效的事件?

回答by Gabriel Llamas

You have to use the readline module and listen for a SIGINT event:

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

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

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

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

回答by Meirion Hughes

I'm not sure as of when, but on node 8.x and on Windows 10 the original question code simply works now.

我不确定什么时候,但在节点 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 );

enter image description here

在此处输入图片说明

also works with a windows command prompt.

也适用于 Windows 命令提示符。

回答by tfmontague

Unless you need the "readline" import for other tasks, I would suggest importing "readline" once the program has verified that it's running on Windows. Additionally, for those who might be unaware - this works on both Windows 32-bit and Windows 64-bit systems (which will return the keyword "win32"). Thanks for this solution Gabriel.

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

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

回答by Pero P.

Currently there is still no support in node for capturing the windows console control events, so there are no equivalents to the POSIX signals:

目前 node 中仍然不支持捕获 windows 控制台控制事件,因此没有与 POSIX 信号等效的信号:

https://github.com/joyent/node/issues/1553

https://github.com/joyent/node/issues/1553

However the tty module documentationdoes give an example of a mechanism to capture the key presses in order to initiate a graceful shutdown, but then this does only work for ctrl+c.

然而tty 模块文档确实给出了一个机制的例子,用于捕获按键以启动正常关闭,但这仅适用于ctrl+ c

var tty = require('tty');

process.stdin.resume();
tty.setRawMode(true);

process.stdin.on('keypress', function(char, key) {
  if (key && key.ctrl && key.name == 'c') {
    console.log('graceful exit of process %d', process.pid);
    process.exit();
  }
});

回答by Heinrich Ulbricht

Nowadays it just workson all platforms, including Windows.

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

The following code logs and then terminates properly on Windows 10:

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

process.on('SIGINT', () => {
    console.log("Terminating...");
    process.exit(0);
});

回答by mekwall

Since node.js 0.8 the keypressevent no longer exists. There is however an npm package called keypressthat reimplements the event.

从 node.js 0.8 开始,该keypress事件不再存在。然而,有一个名为keypress的 npm 包可以重新实现该事件。

Install with npm install keypress, then do something like:

安装npm install keypress,然后执行以下操作:

// Windows doesn't use POSIX signals
if (process.platform === "win32") {
    const keypress = require("keypress");
    keypress(process.stdin);
    process.stdin.resume();
    process.stdin.setRawMode(true);
    process.stdin.setEncoding("utf8");
    process.stdin.on("keypress", function(char, key) {
        if (key && key.ctrl && key.name == "c") {
            // Behave like a SIGUSR2
            process.emit("SIGUSR2");
        } else if (key && key.ctrl && key.name == "r") {
            // Behave like a SIGHUP
            process.emit("SIGHUP");
        }
    });
}