In Node.js, we can configure the 'readline'
module to emit 'keypress'
events like this:
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
Then, we can listen to keypress events like this (example listens to Ctrl+c ):
process.stdin.on('keypress', (str, key) => {
if (key.ctrl && key.name === 'c') {
// do stuff
}
});
This works very well, but I can't find any documentation about the 'keypress'
event at https://nodejs.org/en/docs/.
So my question is: where is the documentation about the arguments used when my 'keypress'
-callback is called?
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
Attach an event to the input box. like onkeypress event. Call a function when that event happens and pass the event parameter in it. In the called function, identify the key pressed.
To prevent the poll phase from starving the event loop, libuv (the C library that implements the Node. js event loop and all of the asynchronous behaviors of the platform) also has a hard maximum (system dependent) before it stops polling for more events.
This detail is specified here because:
The process.stdin
is a duplex stream and calling emitKeypressEvents(<IN/OUT>)
will cause that readline
module will read from the process.stdin
then it will parse the data and then will emit the event writing to the output
stream calling write
, because of this the docs you are looking for are written on that function.
emitKeypressEvents
set the same input param as input and output, instead in createInterface
you can define one for input and one for output (where you must attach the on(keypress)
event.
A little playground to understand:
const readline = require('readline');
const { Readable } = require('stream');
const inStream = new Readable({
read() { console.log('in reading'); }
});
let i = 0
setInterval(() => { inStream.push(`${i++}`) }, 1000)
readline.emitKeypressEvents(inStream);
inStream.on('keypress', (...ar) => {
console.log(ar)
});
It's not directly documented, but the readline.emitKeypressEvents()
method causes the given Readable stream to begin emitting keypress
events corresponding to received input:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With