Nick Manning
Nick Manning

Reputation: 2989

Is it possible to programmatically simulate a keypress using the readline library for node.js?

I am trying to test a terminal application I wrote in node.js that asks the user to press keys. After a day of searching, I can't figure out how to get a test script to "press a key".

I finally found something promising in the docs for the readline module.

rl.write allows one to pass a key argument instead of a string. It even says explicitly, "The rl.write() method will write the data to the readline Interface's input as if it were provided by the user."

So I have the following:

const readline = require('readline');

const rl_interface = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});


readline.emitKeypressEvents(rl_interface.input);
rl_interface.input.setRawMode(true);


rl_interface.input.on('keypress', (str, key) => {
    console.log('data receieved')
    rl_interface.close();
})

rl_interface.write(null, { name:'g' });

I expect the last line to fire the keypress event, log "data received", and close out of the program. But this doesn't happen.

What am I missing here?

Upvotes: 3

Views: 973

Answers (1)

Priyansh Garg
Priyansh Garg

Reputation: 96

I was stuck on the same problem and just found the solution. We can simulate a keypress by directly emitting a keypress event from process.stdin.

In the code, just replace the last line with

process.stdin.emit('keypress', null, {name: 'g'});

and it will run as expected.

Upvotes: 1

Related Questions