I’m using readline.emiteKeypressEvents(process.stdin)
to read user input letter by letter. This is part of a terminal tool I’m creating and this part of code is stored in a script called liveinput.js
.
I’d like to exit the script to move to an another one and using process.exit()
unfortunately closes the entire program. Forcing an another function inside of the script bricks the terminal completely that even CTRL+C cannot fix.
Is there a way to say: ‘I’d like to close this current input stream, but not the entire program!’
I’ve tried process.exit()
, making it an interface, removing listeners and so much more.
I’ll try to crop the code that the “irrelevant” parts are cropped out.
import * as readline from "node:readline";
import fs from "fs";
const stopListen = () => process.stdin.removeAllListeners('keypress');
export function liveInput(socket, terminalStart){
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY){
process.stdin.setRawMode(true);
}
let text = fs.readFileSync("./txt/current_text.txt", "utf8");
console.clear();
console.log("Liveinput:n" + text + "<");
readInput();
function readInput() {
// Exit with ESC or Ctrl+C
process.stdin.on("keypress", (str, key) => {
if (key.seq === "escape") {
// Close this loop, but no the whole program!!!
} else if (key.name === 'backspace') {
text = text.slice(0, -1);
} else if (key.name === 'space') {
text += ' ';
} else if (str && str.length === 1 && !key.ctrl && !key.meta) {
text += str;
}
console.clear();
console.log("Liveinput:n" + text + "<");
});
}
}