在做一些自动化任务时,比如 测试登录表单、模拟终端输入 或者 桌面自动化,我们可能需要让程序帮我们敲键盘。node-key-sender 是一个轻量级的 Node.js 库,可以直接调用键盘事件,甚至能设置输入间隔,模拟真人输入。
本文将带你一步步实现一个小示例:输入一串数字,然后自动敲下回车。
1. 安装 node-key-sender
首先在项目中安装依赖:
npm install node-key-sender
安装完成后,就可以在 Node.js 脚本里直接使用了。
2. 最简单的输入
比如我们要输入 hello,只需要这样写:
const keySender = require('node-key-sender');
// 直接输入字符串
keySender.sendText("hello");
运行脚本后,你的光标位置(比如记事本、浏览器输入框)就会自动输入 hello。
3. 批量输入 + 延迟(模拟真人打字)
为了让输入更自然,我们可以用 批处理 (Batch) 的方式,一个键一个键地敲,同时设置输入间隔。
例如,输入 654321:
const keySender = require('node-key-sender');
function getHumanDelay() {
// 模拟真人打字延迟:80 ~ 200 毫秒之间
return Math.floor(Math.random() * 120) + 80;
}
keySender.startBatch()
.batchTypeKey('6', getHumanDelay())
.batchTypeKey('5', getHumanDelay())
.batchTypeKey('4', getHumanDelay())
.batchTypeKey('3', getHumanDelay())
.batchTypeKey('2', getHumanDelay())
.batchTypeKey('1', getHumanDelay())
.sendBatch();
运行后,你会看到数字一个个慢慢输入,就像人手动敲键盘一样。
4. 加入回车键
很多时候输入完需要按 回车,比如输入密码后提交。
在 node-key-sender 里,可以直接使用 enter 键。
改造一下上面的代码:
keySender.startBatch()
.batchTypeKey('6', getHumanDelay())
.batchTypeKey('5', getHumanDelay())
.batchTypeKey('4', getHumanDelay())
.batchTypeKey('3', getHumanDelay())
.batchTypeKey('2', getHumanDelay())
.batchTypeKey('1', getHumanDelay())
.batchTypeKey('enter', getHumanDelay()) // 👈 自动按下回车
.sendBatch();
这样输入完 654321 之后,就会自动敲一个回车。
5. 封装一个函数:一行搞定
为了更方便,可以把逻辑封装成一个函数:
function typeWithEnter(text) {
const batch = keySender.startBatch();
text.split("").forEach(char => {
batch.batchTypeKey(char, getHumanDelay());
});
batch.batchTypeKey("enter", getHumanDelay()); // 最后回车
batch.sendBatch();
}
// 使用
typeWithEnter("654321");
以后只要调用 typeWithEnter("你的字符串"),就能自动输入并回车。
6. 总结
通过 node-key-sender,我们可以在 Node.js 里轻松实现:
-
自动键盘输入(支持字符串/按键)
-
输入间隔控制(模拟真人打字)
-
自动提交(加入
enter回车)
这在做 自动化测试、桌面脚本、甚至 游戏辅助 时都非常有用。
👉 建议:你可以尝试把 getHumanDelay() 的范围调大(比如 200 ~ 600ms),效果会更像人类输入。
Web前端(W3Cways.com) - Web前端学习之路