0.0.2 • Published 5 years ago

read-one-keypress v0.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

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

namedescription
receiveSigintWhether 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.
receiveEofWhether 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:

stringdescription
sigintkeycode 3, generated by typing control-C
eofkeycode 4, generated by typing control-D
tabkeycode 9
returnkeycode 13
deletekeycode 127
upansi escape code CUU – Cursor Up
downansi escape code CUD – Cursor Down
leftansi escape code CUB – Cursor Back
rightansi escape code CUF – Cursor Forward

Example

while (true) {
    const keypress = await readOneKeypress({receiveSigint: true});
    console.log(`you just pressed: ${keypress}`);

    if (keypress === 'sigint')
        break;
}