Reputation: 81
I have a little utility written in node.js that does some real-time data capture. I'd like to augment it so it also records whether a particular key is pressed on the keyboard at which time during the capture. (This allows me to "mark" the time in the data capture when some event happened).
But how do I detect whether a given key is pressed/down on the keyboard from node.js? Something like readline won't work because it's line-based, and waits until CR is entered. (The capture needs to continue in real time.) Instead, it needs to access the keyboard on a fairly low level to get "the state of key X right now", returning pressed or not-pressed.
Is there such a thing in node.js?
Upvotes: 6
Views: 12054
Reputation: 51
iohook
support only nodejs v8.x - v15.x
readline
support current nodejs v19.x
Try install readline with command: npm I readline
var readline = require('readline');
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
console.log('press q to exit, or any key to print log');
process.stdin.on('keypress', (chunk, key) => {
if (key && key.name == 'q'){
process.exit();
}
console.log({key});
});
Upvotes: 4
Reputation: 1679
From here ;
let readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.on('keypress', (ch, key) => {
console.log('got "keypress"', ch, key);
if (key && key.ctrl && key.name == 'c') {
process.stdin.pause();
}
});
process.stdin.setRawMode(true);
Upvotes: 1
Reputation: 1069
Just use iohook npm module. This is example:
const iohook = require('iohook');
iohook.on("keypress", event => {
console.log(event);
// {keychar: 'f', keycode: 19, rawcode: 15, type: 'keypress'}
});
iohook.start();
But this is question is duplicate for this question
Upvotes: 3