Files
yinx-cli/lib/keyboard.js
2025-12-20 11:51:35 +08:00

38 lines
820 B
JavaScript

import readline from "readline";
let initialized = false;
export function initKeypress() {
if (!initialized) {
readline.emitKeypressEvents(process.stdin);
initialized = true;
}
process.stdin.removeAllListeners("keypress");
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
}
export function onKey(handler) {
process.stdin.on("keypress", handler);
}
export function stopKeypress() {
process.stdin.removeAllListeners("keypress");
if (process.stdin.isTTY) {
process.stdin.setRawMode(false);
}
}
export function waitForKey(message = "按任意键返回...") {
return new Promise(resolve => {
console.log("\n" + message);
initKeypress();
const handler = () => {
stopKeypress();
resolve();
};
process.stdin.once("keypress", handler);
});
}