Node.js Raw Mode with Keystrokes
I find the stuff that people are doing with Node.js incredibly interesting. You here about people using Node.js to control drones, Arduinos, and a host of other devices. I took advantage of Node.js to create a Roku Remote, a project that was fun and easier than I thought it would be. There was one piece of this experiment that was difficult, however: listening for keystrokes within the same shell that executed the script.
The process for using the remote is as follows:
- Execute the script to connect to your Roku:
node remote - In the same shell, use arrow keys and hot keys to navigate the Roku
- Press
CONTROL+Cto kill the script
The following JavaScript code is what I needed to use to both listen for keystrokes within the same shell once the script had been started:
// Readline lets us tap into the process events
const readline = require('readline');
// Allows us to listen for events from stdin
readline.emitKeypressEvents(process.stdin);
// Raw mode gets rid of standard keypress events and other
// functionality Node.js adds by default
process.stdin.setRawMode(true);
// Start the keypress listener for the process
process.stdin.on('keypress', (str, key) => {
// "Raw" mode so we must do our own kill switch
if(key.sequence === '\u0003') {
process.exit();
}
// User has triggered a keypress, now do whatever we want!
// ...
});
The code above turns your Node.js script into an active wire for listening to keypress events. With my Roku Remote, I pass arrow and letter keypress events directly to the Roku via a REST API (full code here). I love that Node.js made this so easy -- another reason JavaScript always wins!




I like a lot that you are writing about messing with Iot using nodejs! Looking forward to see more! Thanks!