本文介绍了在 Node.js 中检测 CTRL+C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个 SO question 中得到了这段代码,但是 node 抱怨使用 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 的原生 + 处理程序,所以当我按下它时它甚至不会退出节点.如何在Windows中成功处理+?

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

推荐答案

如果你想捕捉中断信号SIGINT,你不需要从键盘读取.nodejsprocess 对象暴露了一个中断事件:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 11:31
查看更多