简体   繁体   中英

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. 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. 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. 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. In this case I'd like a way to see if ctrl+h was pressed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM