使用 RobotJS 实现 NodeJS 桌面自动化(但这个程序可能会让你被录用或被解雇😄)
前段时间,我看到一个“软件工程师的一天”的 meme 视频,其中工程师编写了一个脚本,让他的电脑自动开机,打开 Slack,并在他睡觉时定期移动鼠标,让他看起来同时在线并且正在工作。
我们将使用RobotJS 模块用 NodeJS 编写一个类似的程序。RobotJS 是一个跨平台的桌面自动化库。
这仅用于教育目的。😊

步骤
- 运行
npm install yargs robotjs
以安装所需的依赖项。 - 创建一个
app.js
文件并粘贴下面的代码。(我会解释代码):
// app.js
const yargs = require("yargs");
const { hideBin } = require("yargs/helpers");
const arg = yargs(hideBin(process.argv))
.command("$0 [interval]", true, (yargs) => {
yargs
.positional("interval", {
type: "number",
describe: "the interval in second",
})
.default("interval", 60); // 60 seconds default
})
.usage("runs a desktop automator to run key your mmouse move at interval")
.example(
"$0 -mk 3",
"moves the mouse and press the keyboard after three seconds"
)
.option("m", {
description: "enable the mouse",
type: "boolean",
})
.option("k", {
description: "enable the keyboard",
type: "boolean",
})
.default("m", true)
.help("h").argv;
上面的代码配置了应用程序所需的参数选项,并定义了一个 CLI 接口来描述应用程序运行时的情况node app.js -h
。我们将提供仅运行键盘按下 ( -k
)、鼠标移动 ( -m
) 或两者 ( -mk
) 的选项,并定义事件的时间间隔(以秒为单位)。
我在这里写了一篇关于解析 NodeJS CLI 参数的文章。
- 我们将定义布尔变量来确定要执行的操作:
let is_both;
let is_mouse;
let is_keyboard;
- 接下来,我们将定义移动鼠标和按下键盘的函数
function moveMouseBackAndForth() {
robot.moveMouseSmooth(200, 200);
robot.moveMouseSmooth(400, 400);
}
function pressKeyBoard() {
robot.keyTap("shift");
}
- 然后,我们将根据传递的参数调用函数。整个代码如下所示:
const yargs = require("yargs");
const robot = require("robotjs");
const { hideBin } = require("yargs/helpers");
let is_both;
let is_mouse;
let is_keyboard;
const arg = yargs(hideBin(process.argv))
.command("$0 [interval]", true, (yargs) => {
yargs
.positional("interval", {
type: "number",
describe: "the interval in second",
})
.default("interval", 60); // 60 seconds default
})
.usage("runs a desktop automator to run key your mmouse move at interval")
.example(
"$0 -mk 3",
"moves the mouse and press the keyboard after three seconds"
)
.option("m", {
description: "enable the mouse",
type: "boolean",
})
.option("k", {
description: "enable the keyboard",
type: "boolean",
})
.default("m", true)
.help("h").argv;
let { m, k, interval } = arg;
// multiply seconds by 1000 to get milliseconds
interval = interval * 1000;
if (m && k) is_both = true;
else {
if (m) is_mouse = true;
else if (k) is_keyboard = true;
}
function moveMouseBackAndForth() {
robot.moveMouseSmooth(200, 200);
robot.moveMouseSmooth(400, 400);
}
function pressKeyBoard() {
robot.keyTap("shift");
}
if (is_both) {
setInterval(() => {
moveMouseBackAndForth();
pressKeyBoard();
}, interval);
} else if (is_keyboard) setInterval(pressKeyBoard, interval);
else {
setInterval(moveMouseBackAndForth, interval);
}
- 运行
node app.js -m 3
仅以 3 秒的间隔移动我们的鼠标。
感谢您的阅读。除了按下键盘之外,您还希望程序执行其他操作吗?
你可以从Github gist获取代码
我将非常感谢您的反馈和问题。
文章来源:https://dev.to/zt4ff_1/nodejs-desktop-automation-with-robotjs-but-with-a-program-that-could-get-you-hired-fired-fj