Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

event handling - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...