在Windows上处理Node.js中的CTRL + C事件 [英] Handling CTRL+C event in Node.js on Windows

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

问题描述

我正在开发一个节点项目,我想在退出时写一些内存到文件。我认为它很简单:

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

但是,当收到CTRL + C时,此代码不会执行(在Windows上)。鉴于这是退出Node的实际方法,这似乎有点问题。

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.

此时我试图处理信号(on。('SIGINT',相反,这导致错误:

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


node.js:218
throw e; // process.nextTick错误,或首次勾选'错误'事件
^错误:在EventEmitter没有这样的模块
。 (node.js:403:27)对象的
。 (C:\ Users \Mike\workspace\NodeDev\src\server.js:5:9)
在Module._compile(module.js:434:26)
at Object.js(module.js:452:10)
在Module.load(module.js:353:32)
在Function._load(module.js:310:12)
在Array.0(module.js:472:10)
在EventEmitter._tickCallback(node.js:209:41)

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)

关闭快速Google和它出现节点根本无法处理信号在Windows和CTRL + C实际上不会触发退出事件。上面的错误不应该在* Nix系统上退出。

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.

但是,关闭Windows平台对我来说不是一个有效的选项,所以我需要一个解决方法。有没有办法处理Node中的On Exit事件,这是由用户按CTRL + C终止脚本引起的?

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?

推荐答案

我用这段代码来听取密钥。它似乎适用于 CTRL + C 以及Windows。

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

但是它再次只适用于 CTRL + C 作为组合键,而不是其他任何东西。当然,您可以将函数绑定到 process.on(exit,并在中调用它,如果阻止下面。

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

这篇关于在Windows上处理Node.js中的CTRL + C事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆