Node.js JavaScript: Simulate Keypress on Server (Like a Macro)

Nimaid picture Nimaid · Feb 18, 2014 · Viewed 15.7k times · Source

I am trying to get a node.js script to simulate a keypress, such as the up arrow or the a button. Specifically, I am trying to make a clone of Twitch Plays Pokemon. Basically, whenever a command (up, down, left, right, a, b, select, start) is sent via IRC, the server simulates a keypress, which in turn controls a gameboy emulator. So far, I have written this with the IRC module for node.js:

var config = {
    channels: ["#tron"],
    server: "irc.freenode.net",
    botName: "wyatt"
};

var irc = require("irc");

var bot = new irc.Client(config.server, config.botName, {
    channels: config.channels
});

var commandHandler = function(from, text) {
    if(text.toLowerCase() === "up"||text.toLowerCase() === "down"||text.toLowerCase() === "left"||text.toLowerCase() === "right"||text.toLowerCase() === "a"||text.toLowerCase() === "b"||text.toLowerCase() === "select"||text.toLowerCase() === "start") {
        bot.say(config.channels[0], from.toUpperCase() + " sent the " + text.toUpperCase() + " command!");
    } else {
        bot.say(config.channels[0], from.toUpperCase() + ", that wasn't a valid command!");
    }
};

bot.addListener("message", function(from, to, text, message) {
    commandHandler(from, text);
});

To run my script, I type node scriptName.js into a command prompt. I am using Windows 7.

This connects to the freenode channel #tron, which I am using for testing purposes, as it seems to be mainly dormant.

When a user inputs one of the accpted commands, it sends a message like "NIMAID sent the LEFT command!", otherwise it sends "NIMAID, that wasn't a valid command!". As it is, it works flawlessly. So all I need to do is find a way to send a keypress and the final script is just a switch statement away.

The trouble is that any references I can find by searching the internet talks about using node.js in a browser environment, with JQuery or something similar. I need to send keypresses to an emulator.

tldr: I need to send keypresses from a node.js script to an application running on the windows 7 server desktop.

Is there any way to do this?

Answer

Kyle Paulsen picture Kyle Paulsen · Jan 25, 2015

I made a node module to do this too: https://github.com/kylepaulsen/kbm-robot

var robot = require("kbm-robot");

robot.startJar();

robot.press("alt")
    .press("tab")
    .sleep(100)
    .release("tab")
    .release("alt")
    .sleep(100)
    .typeString("Hello World!")
    .go()
    .then(robot.stopJar);