Node.js Raw Mode with Keystrokes

By  on  

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:

  1. Execute the script to connect to your Roku:  node remote
  2. In the same shell, use arrow keys and hot keys to navigate the Roku
  3. Press CONTROL+C to 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!

Recent Features

Incredible Demos

  • By
    Reverse Element Order with CSS Flexbox

    CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics...

  • By
    MooTools 1.3 Browser Object

    MooTools 1.3 was just released and one of the big additions is the Browser object.  The Browser object is very helpful in that not only do you get information about browser type and browser versions, you can gain information about the user's OS, browser plugins, and...

Discussion

  1. Haldun

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

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!