How to read keystrokes from standard input in nodejs example

Sometimes, Nodejs code allows listening to the keyboard events to do some processing related to hardware or script automation.

Keyboard has different events.

  • keypress
  • keydown

Nodejs has an inbuilt object called a process that has a stdin function to read the stream from the keyboard network.

Nodejs read keystrokes data and display it to the user

In this example, Create an stdin object using one the below approaches

var stdin = process.openStdin();
or;
var stdin = process.openStdin();

if you are using the ES6 version of javascript, You can import with the below import statement

import process from "process";

Next, read from the keyboard using the standard input resume method as seen below

stdin.resume();

Next, catch the key events using the process with the data event.

It initializes with the stdin stream.

Here is a code or nodejs keystrokes example. key.js:

var stdin = process.openStdin();

stdin.resume();
stdin.on("data", function (keydata) {
  process.stdout.write("output: " + keydata);
});

This will read the keyboard strokes and output them to the console.

Running node key.jsgives the following output

node key.js

testkeystrokes
data:testkeystrokes

nodejs keypress events to read from standard input

In this example, each character keystroke is read and displayed as a character, and key meta information is displayed.

  • First, Import the readline module into the code
  • emitKeyPressEvents to read the keypress events from standard input
  • set Ram mode to true
  • write an event for a keypress to track keystrokes

Here is an example of a nodejs keypress event keypress.js:

const readlineModule = require("readline");

readlineModule.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on("keypress", (charater, key) => {
  console.log(character);
  console.log(key);
});

Output on running the above code is

B:\blog\jswork>node keypress.js
a
{ sequence: 'a', name: 'a', ctrl: false, meta: false, shift: false }

Conclusion

You learned how to read keystrokes events from standard input and display.