{

How to read keystrokes from standard input in nodejs example


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 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 on with 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 to the console.

Running node key.js gives 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 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 for 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(charater)
  console.log(key)
})

Output on running 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.