优化卡死的问题

This commit is contained in:
yinsx
2025-12-20 14:13:59 +08:00
parent 3098796a08
commit ad60f8c3ec
7 changed files with 495 additions and 108 deletions

View File

@ -1,37 +1,48 @@
import readline from "readline";
let initialized = false;
let currentHandler = null;
function ensureRawMode(enabled) {
if (process.stdin.isTTY) {
process.stdin.setRawMode(enabled);
}
}
export function initKeypress() {
// 清理所有keypress监听器
process.stdin.removeAllListeners("keypress");
currentHandler = null;
// 初始化readline只需一次
if (!initialized) {
readline.emitKeypressEvents(process.stdin);
initialized = true;
}
process.stdin.removeAllListeners("keypress");
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
ensureRawMode(true);
}
export function onKey(handler) {
// 清理旧的监听器
process.stdin.removeAllListeners("keypress");
currentHandler = handler;
process.stdin.on("keypress", handler);
}
export function stopKeypress() {
process.stdin.removeAllListeners("keypress");
if (process.stdin.isTTY) {
process.stdin.setRawMode(false);
}
currentHandler = null;
ensureRawMode(false);
}
export function waitForKey(message = "按任意键返回...") {
return new Promise(resolve => {
console.log("\n" + message);
initKeypress();
const handler = () => {
onKey(() => {
stopKeypress();
resolve();
};
process.stdin.once("keypress", handler);
});
});
}