jayarjo
jayarjo

Reputation: 16726

Is it possible to simulate keyboard/mouse event in NodeJS?

Imagine that a NodeJS module, when invoked from console, outputs some introductory messages and then waits for user input (click enter or esc). This module already has and does everything we require, except that - wait-for-user-input prompt. So we wonder (I'm personally very new to NodeJS) if it is possible to execute console module programmatically and trigger an input event on it, so that it doesn't wait and proceed with the job right away?

Upvotes: 21

Views: 39215

Answers (5)

ReallyBoringPerson
ReallyBoringPerson

Reputation: 133

Responding to @Venryx. They are right that robotjs is going to have a delay, especially if you have to load node first, however, if you already have node loaded, it may be worth trying out

robot.setKeyboardDelay(0)

The default setting for a delay is 10ms. This helped me tremendously.

Upvotes: 4

Venryx
Venryx

Reputation: 17999

I've tried robotjs and node-key-sender, but they cause a substantial amount of delay/stuttering per key-event. (especially noticeable when sending them frequently)

To resolve this, I found a way to use node-ffi-napi to call the Windows user32 SendInput function directly: https://stackoverflow.com/a/50412529/2441655

In my case at least, this achieved substantially better performance. (however, a drawback is that it only works on Windows, of course)

Upvotes: 3

GorvGoyl
GorvGoyl

Reputation: 49270

As Jason mentioned you could use RobotJS for key simulation but there are couple of steps require to correctly build robotJS for Windows paltform:

  1. You would need windows build tools so run npm install --global windows-build-tools (would take some time as it's around 120MB)
  2. run npm install robotjs --save-dev
    You're done!.
    If this is for electron app then you would also require below 3rd step:
  3. run npm rebuild --runtime=electron --target=1.7.9 --disturl=https://atom.io/download/atom-shell --abi=57

    (1.7.9 is my electron --version and abi is for my corresponding node --version 8.7 installed, you can check abi version for node version here [look for NODE_MODULE_VERSION column])

Upvotes: 18

computeiro
computeiro

Reputation: 603

node-key-sender library is an alternative to RobotJs if you just need to send keys to your operational system. It is cross platform and very small lib.

Install it with npm install --save-dev node-key-sender.

And send "enter" to the keyboard using:

var ks = require('node-key-sender');
ks.sendKey('enter');

Check out the documentation page: https://www.npmjs.com/package/node-key-sender.

Upvotes: 8

Jason Stallings
Jason Stallings

Reputation: 1473

You could use possibly use RobotJS for this.

Example code:

var robot = require("robotjs");

// Type user's password or something. 
robot.typeString("abc123");

Upvotes: 31

Related Questions