Handling CTRL+C event in Node.js on Windows

2020-07-06 08:05发布

问题:

I am working on a node project where I want to write some memory to file when exiting. I figured it was as simple as:

process.on('exit', function () {
 //handle your on exit code
 console.log("Exiting, have a nice day");
});

However, this code does not execute (on Windows) when CTRL+C is received. Given this is the defacto way to exit Node, this seems a bit of a problem.

At this point I tried to handle the signal ( on.('SIGINT',...) ) instead, which results in the error:

node.js:218 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: No such module at EventEmitter. (node.js:403:27) at Object. (C:\Users\Mike\workspace\NodeDev\src\server.js:5:9) at Module._compile (module.js:434:26) at Object..js (module.js:452:10) at Module.load (module.js:353:32) at Function._load (module.js:310:12) at Array.0 (module.js:472:10) at EventEmitter._tickCallback (node.js:209:41)

Off to a quick Google and it appears Node simply doesn't handle signals on Windows and CTRL+C does not in fact trigger the "exit" event. The above error should not exit on a *Nix system.

However, switching off the Windows platform is not a valid option for me, so I need a workaround. Is there a way to handle On Exit events in Node that are caused by the user pressing CTRL+C to terminate the script?

回答1:

I used this piece of code for listening for keys. It seems to work for CTRL + C as well on Windows.

But then again it only works for CTRL + C as a key combination, not anything else. Of course, you could both bind a function to process.on("exit", and call it inside the if block below.

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