在Node.js中检测CTRL + C [英] Detecting CTRL+C in Node.js
问题描述
我从另一个SO问题得到了这段代码,但是节点抱怨使用process.stdin.setRawMode而不是tty,所以我更改了它.
I got this code from a different SO question, but node complained to use process.stdin.setRawMode instead of tty, so I changed it.
之前:
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);
之后:
process.stdin.setRawMode(true);
process.stdin.on("keypress", function(chunk, key) {
if(key && key.name === "c" && key.ctrl) {
console.log("bye bye");
process.exit();
}
});
无论如何,它只是创建一个完全不响应的节点进程,什么也不做,第一个抱怨tty
,然后抛出一个错误,第二个什么都不做,并禁用Node的本机 CTRL + C 处理程序,因此当我按它时它甚至都不会退出节点.如何在 Windows 中成功处理 Ctrl + C ?
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?
推荐答案
如果要捕获中断信号SIGINT
,则无需从键盘读取. nodejs
的process
对象公开了一个中断事件:
If you're trying to catch the interrupt signal SIGINT
, you don't need to read from the keyboard. The process
object of nodejs
exposes an interrupt event:
process.on('SIGINT', function() {
console.log("Caught interrupt signal");
if (i_should_exit)
process.exit();
});
编辑:如果没有解决方法,则无法在Windows上使用. 在此处查看
Edit: doesn't work on Windows without a workaround. See here
这篇关于在Node.js中检测CTRL + C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!