在 Node.js 中检测 CTRL+C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20165605/
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 16:20:22  来源:igfitidea点击:

Detecting CTRL+C in Node.js

node.jsevent-handlingcopy-paste

提问by user3025492

I got this code from a different SO question, but node complained to use process.stdin.setRawMode instead of tty, so I changed it.

我从一个不同的 SO 问题中得到了这段代码,但是节点抱怨使用 process.stdin.setRawMode 而不是 tty,所以我改变了它。

Before:

前:

var tty = require("tty");

process.openStdin().on("keypress", function(chunk, key) {
  if(key && key.name === "c" && key.ctrl) {
    console.log("bye bye");
    process.exit();
  }
});

tty.setRawMode(true);

After:

后:

process.stdin.setRawMode(true);
process.stdin.on("keypress", function(chunk, key) {
  if(key && key.name === "c" && key.ctrl) {
    console.log("bye bye");
    process.exit();
  }
});

In any case, it's just creating a totally nonresponsive node process that does nothing, with the first complaining about tty, then throwing an error, and the second just doing nothing and disabling Node's native CTRL+Chandler, so it doesn't even quit node when I press it. How can I successfully handle Ctrl+Cin Windows?

在任何情况下,它只是创建一个完全无响应的节点进程,它什么都不做,第一个抱怨tty,然后抛出错误,第二个什么都不做并禁用 Node 的本机CTRL+C处理程序,所以当我时它甚至不退出节点按下。如何在Windows 中成功处理Ctrl+ ?C

回答by slezica

If you're trying to catch the interrupt signal SIGINT, you don't need to read from the keyboard. The processobject of nodejsexposes an interrupt event:

如果您试图捕捉中断信号SIGINT,则不需要从键盘读取。的process对象nodejs暴露一个中断事件:

process.on('SIGINT', function() {
    console.log("Caught interrupt signal");

    if (i_should_exit)
        process.exit();
});

Edit: doesn't work on Windows without a workaround. See here

编辑:如果没有解决方法,则无法在 Windows 上运行。看这里

回答by honzajde

For those who need the functionality, I found death (npm nodule, hah!).

对于那些需要功能的人,我发现了死亡(npm 结节,哈哈!)

Author also claimsit works on windows:

作者还声称它适用于 Windows:

It's only been tested on POSIX compatible systems. Here's a nice discussion on Windows signals, apparently, this has been fixed/mapped.

它仅在 POSIX 兼容系统上进行了测试。这是关于 Windows 信号的一个很好的讨论,显然,这已被修复/映射。

I can confirm CTRL+Cworks on win32 (yes, I am surprised).

我可以确认CTRL+C在 win32 上工作(是的,我很惊讶)。