如何在node.js中检测是否按下了某个键?

ddrv8njm  于 2023-03-17  发布在  Node.js
关注(0)|答案(3)|浏览(164)

我在node.js中编写了一个小实用程序,它可以进行一些实时数据捕获,我想对其进行扩展,以便它还记录在捕获期间的哪个时间是否按下了键盘上的某个特定键(这允许我在数据捕获中“标记”某个事件发生的时间)。
但是如何从node.js检测键盘上的某个键是否被按下呢?类似readline的命令不起作用,因为它是基于行的,并且要等待输入CR。(捕获需要真实的继续。)相反,它需要在相当低的级别访问键盘以获取“当前键X的状态”,返回按下或未按下。
node.js中有这样的东西吗?

prdp8dxp

prdp8dxp1#

只需使用iohook npm module。这是一个示例:

const iohook = require('iohook');
iohook.on("keypress", event => {
  console.log(event);
  // {keychar: 'f', keycode: 19, rawcode: 15, type: 'keypress'}
});
iohook.start();

但这道题与这道题重复

yvfmudvl

yvfmudvl2#

从这里;

let readline = require('readline');

readline.emitKeypressEvents(process.stdin);

process.stdin.on('keypress', (ch, key) => {
  console.log('got "keypress"', ch, key);
  if (key && key.ctrl && key.name == 'c') {
    process.stdin.pause();
  }
});

process.stdin.setRawMode(true);
56lgkhnf

56lgkhnf3#

iohook仅支持节点js v8.x - v15.x
读取行支持当前节点js v19.x
尝试使用以下命令安装readline:npm i读取行

var readline = require('readline');

readline.emitKeypressEvents(process.stdin);

if (process.stdin.isTTY)
    process.stdin.setRawMode(true);

console.log('press q to exit, or any key to print log');

process.stdin.on('keypress', (chunk, key) => {
  if (key && key.name == 'q'){
    process.exit();
  }
  console.log({key});
});

相关问题