[英]Node js how to get list of keys pressed
I'm writing a command line app using Node.js. I'm trying to get keypresses from stdin.我正在使用 Node.js 编写命令行应用程序。我正在尝试从标准输入获取按键。 Here's what I've tried so far:到目前为止,这是我尝试过的:
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (str, key) => {
console.log(str)
console.log(key)
})
This works pretty well.这很好用。 It gets all letters and I can see if some modifiers were pressed such as control/shift.它获取所有字母,我可以看到是否按下了某些修饰符,例如控制/移位。 But it doesn't register some key combinations like shift+alt+up.但它没有注册一些组合键,如 shift+alt+up。 I would like a method to just get a list of keys pressed so I can parse combos like that.我想要一种方法来获取按下的键列表,这样我就可以像那样解析组合。
Also, some key combos are registered as ansi escape sequences.此外,一些键组合被注册为 ansi 转义序列。 For example:例如:
// ctrl+a
{ sequence: '\x01', name: 'a', ctrl: true, meta: false, shift: false }
// ctrl+h
{
sequence: '\b',
name: 'backspace',
ctrl: false,
meta: false,
shift: false
}
Here ctrl+a is registered as 'a' with control pressed, but ctrl+h is registered as backspace.这里 ctrl+a 在按下控制键时注册为 'a',但 ctrl+h 注册为退格键。 In this case I'd like a way to see if ctrl+h was pressed.在这种情况下,我想要一种方法来查看是否按下了 ctrl+h。
The stdin is based on byte streams, so it only responds to bytes.标准输入是基于字节流的,所以它只响应字节。 Whether the corresponding keystroke will input bytes depends on a higher layer, such as the operating system.对应的击键是否输入字节取决于更高层,例如操作系统。 If you want to detect keystrokes, you have to use proprietary APIs from the higher layer.如果你想检测击键,你必须使用来自更高层的专有 API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.