问题描述
我正在用 NodeJS 编写一个命令行实用程序,我想从用户那里收集原始键盘输入。但是,我想防止他们长按某个键并重复该键直到他们释放该键。每次按键只能返回一个字符,而不管按键被按下多长时间。
const readline = require('readline')
readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)
process.stdin.on('keypress',(str,key) => {
process.stdout.write(str)
// more code
if (key.ctrl && key.name === 'c') {
process.exit(0)
}
})
如何防止密钥重复?
解决方法
也许您可以存储该值并设置计时器以在按下相同键时解锁。例如:
const readline = require("readline");
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
let lastKey = "";
let lastKeyTime = 0;
process.stdin.on("keypress",(str,key) => {
// Check same key with time 0.6 sec
if (lastKey == key.sequence && new Date().getTime() - lastKeyTime < 600) {
lastKeyTime = new Date().getTime();
return;
}
// Print
process.stdout.write(str);
// Add data
lastKey = key.sequence;
lastKeyTime = new Date().getTime();
if (key.ctrl && key.name === "c") {
process.exit(0);
}
});