How to read keystrokes from standard input in nodejs example


Some times, Nodejs code allows to listen the keyboard events to do some processing related to hardware or script automation.

Keyboard has different events

  • keypress
  • keydown

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

Nodejs read keystork data and display to 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 ES6 version of javascript, You can import with below import statement

import process from 'process';

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

stdin.resume(); 

Next catch the keyevents using process on with data event

This will initialized with stdin stream

Here is an 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 console

Running node key.js gives 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 display an character and key meta information is displayed.

  • First, Import readline module into code
  • emitKeyPressEvents to read the key press events from standard input
  • set Ram mode to true
  • write a event for 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 an 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.