gpt4 book ai didi

javascript - 在 Windows 上处理 Node.js 中的 CTRL+C 事件

转载 作者:IT老高 更新时间:2023-10-28 23:25:05 24 4
gpt4 key购买 nike

我正在处理一个 Node 项目,我想在退出时将一些内存写入文件。我想这很简单:

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

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

此时我尝试处理信号( on.('SIGINT',...) ),这导致错误:

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 和 it appears Node 根本不处理 Windows 上的信号,并且 CTRL+C 实际上不会触发“退出”事件。上述错误不应在 *Nix 系统上退出。

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

最佳答案

我使用这段代码来监听按键。它似乎也适用于 CTRL + C 在 Windows 上。

但话又说回来,它只适用于 CTRL + C 作为组合键,而不是其他任何东西。当然,你可以将一个函数绑定(bind)到 process.on("exit",并在下面的 if block 中调用它。

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

关于javascript - 在 Windows 上处理 Node.js 中的 CTRL+C 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9199105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com