Detecting CTRL+C in Node.js

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

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+C handler, so it doesn't even quit node when I press it. How can I successfully handle Ctrl+C in Windows?

101705 次浏览

如果您试图捕获中断信号 SIGINT,则不需要从键盘读取。nodejsprocess对象公开一个中断事件:

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

对于那些需要这个功能的人,我找到了 死亡(npm 结节,哈!)

作者也是 声称,它在窗口上工作:

它只在与 POSIX 兼容的系统上进行过测试。

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

NPM 模块 death使用 SIGINTSIGQUITSIGTERM

So basically, all you need to do is:

process.on('SIGINT', () => {});  // CTRL+C
process.on('SIGQUIT', () => {}); // Keyboard quit
process.on('SIGTERM', () => {}); // `kill` command

作为一个旁注,这可能实际上调用 SIGINTSIGQUIT,和 SIGTERM无数次... 不知道为什么,它为我做。

我通过这样做修复了它:

let callAmount = 0;
process.on('SIGINT', function() {
if(callAmount < 1) {
send.success(`✅ The server has been stopped`, 'Shutdown information', 'This shutdown was initiated by CTRL+C.');
setTimeout(() => process.exit(0), 1000);
}


callAmount++;
});

如果您只想检测中断键,那么只需使用 SIGINT

Edit: I didn't realize this post was very old, oh well, it's helpful to others I guess!

if (event.key == "ctrl+c") {
console.log("goodbye");
break;
}