read-one-keypress
v0.0.2
Published
Promise-based API to read a single keypress at a time from stdin
Readme
read-one-keypress
Simple function to read a single keypress from process stdin, using a Promise-based function. Handles terminal codes and (some) ANSI escape codes.
This library is still version 0.x , some known issues are:
- Not all ANSI escape codes are parsed. Currently it just handles the arrow keys.
API
interface Options {
receiveSigint?: boolean
receiveEof?: boolean
}
export default function readOneKeypress(opts?: Options): Promise<string>Options
| name | description |
| ---- | ----------- |
| receiveSigint | Whether the caller wants to receive 'sigint's (generated by pressing control-C in the terminal). The default behavior is to kill the process with SIGINT. If this is true then you'll receive a sigint result, then it's up to you to kill the process, if you want. |
| receiveEof | Whether the caller wants to receive 'eof's (generated by pressing control-D in the terminal). The default behavior is to kill the current process. If this is true then you'll receive a eof result, then it's up to you to kill the process, if you want. |
Output
readOneKeypress either returns a one-character string for normal keypresses (parsed as UTF-8), or one of these special strings for terminal codes and escapes:
| string | description |
| ------ | ----------- |
| sigint | keycode 3, generated by typing control-C |
| eof | keycode 4, generated by typing control-D |
| tab | keycode 9 |
| return | keycode 13 |
| delete | keycode 127 |
| up | ansi escape code CUU – Cursor Up |
| down | ansi escape code CUD – Cursor Down |
| left | ansi escape code CUB – Cursor Back |
| right | ansi escape code CUF – Cursor Forward |
Example
while (true) {
const keypress = await readOneKeypress({receiveSigint: true});
console.log(`you just pressed: ${keypress}`);
if (keypress === 'sigint')
break;
}