A package for handling terminal input (mouse, keyboard, clipboard and focus).
npm install tty-eventstty-events is a package for handling events from the terminal, made for interactive, terminal-based applications.
node:readline’s keypress event;
key == "Ctrl+s");
unknownSequence event.
js
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
const term = new (require("tty-events"));
term.on("keypress", (key)=>{
console.log("You pressed %s.", key.toString());
if (key == "Ctrl+c") {
term.pause(); // Exit the program
}
});
`
$3
tty-events supports mouse (VT200 and SGR extended). In order to receive mouse events, the enableMouse() function must be called first.
`js
term.enableMouse();
term.on("mousedown", (ev)=>{
console.log("You clicked at (%i, %i) with the button no. %i.", ev.x, ev.y, ev.button);
});
`
For a highlight tracking example, see the example highlight tracking script.
$3
tty-events supports bracketed paste mode. This feature allows to distinguish between real keystrokes and pasted text from the clipboard. This is useful in applications where certain keys trigger some command. In order to receive paste events, the enableBPM() function must be called first.
`js
term.enableBPM();
term.on("paste", (text)=>{
console.log("You pasted %O.", text);
});
`
$3
Focus events allow an application to stop updating the screen when it's not necessary. In order to receive focus events, the enableFocus() function must be called first.
`js
term.enableFocus();
term.on("focusin", ()=>{
console.log("The terminal received focus.");
});
term.on("focusout", ()=>{
console.log("The terminal lost focus.");
});
`
Important Notes and Limitations
Because of the way terminals work, there are some aspects that might seem unintuitive.
$3
An uppercase letter emits an event with the uppercase letter and with the shift property set to false. This is because there is no way to know if Shift was being pressed (an uppercase letter can be produced with Caps Lock). For example: Shift+Alt+A emits Alt+A instead of Alt+Shift+a.
$3
Some key combinations produce the same output to stdin. Here is a list of the key combinations that may not work as expected:
- Ctrl+Shift+<letter>: Emits Ctrl+ (in lowercase). (The Shift modifier is ignored.)
- Ctrl+H: Emits backspace. (Terminals send \b when Ctrl+H is pressed.)
- Ctrl+I: Emits tab. (Terminals send \t when Ctrl+I is pressed.)
- Ctrl+J: Emits enter. (Terminals send \n when Ctrl+J is pressed.)
- Ctrl+M: Emits enter. (Terminals send \r when Ctrl+M is pressed.)
- Ctrl+[: Emits escape. (Terminals send \x1B when Ctrl+[ is pressed.)
- Shift+F1: Emits f11 in some terminals.
- Shift+F2: Emits f12 in some terminals.
$3
Listening for Esc (escape) is discouraged. Terminals send \x1B` when Esc is pressed, which is the first byte of escape sequences, and this makes the detection unreliable.