In the code below, I'm capturing keypress events and it works fine. When the "s" key is typed, it starts a prompt asking for the user name and prints it. The issue is after using inquirer the keypress event is disrupted. At first, it wasn't capturing keys anymore, I then added the process.stdin.resume(); after using the prompt. Now, the key is captured only after pressing the ENTER key and the key itself is also displayed on the screen as you can see in the picture below.
Here's the code:
import readline from "readline";
import inquirer from "inquirer";
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
let asking = false;
function ask() {
asking = true;
console.log("starting prompt");
inquirer.prompt([
{
type: "input",
name: "name",
message: "What is your name?"
}
])
.then(answers => {
console.log(`Hello ${answers.name}`);
asking = false;
// after using inquirer, we're not capturing the keypress events anymore
// even CTRL+C is not working anymore, so the console is not exiting
// we need to reset the stdin:
process.stdin.resume();
});
}
process.stdin.on("keypress", (str, key) => {
// after adding process.stdin.resume(); in the inquirer prompt,
// we're capturing the keypress events again but only after pressing ENTER key and
// in this case, we are receiving three key events: the key, RETURN and ENTER
if (key.ctrl && key.name === "c") {
process.exit();
}
else {
if (!asking) {
console.log();
console.log(`You pressed the "${str}" key`);
console.log(key);
if (key.name === "s") {
ask();
}
}
}
});
console.log("Before inquirer prompt");
// without this, the console exit after the inquirer prompt
setInterval(() => {
// console.log("Tick");
}, 5000);
and here's the outcome:
