如何捕获node.js中的箭头键

Ros*_*sim 16 utf-8 node.js

所有四个箭头键(左上)的utf8代码是什么?

我正在学习node.js,我试图检测这些键被按下的时间.

这是我做的,但没有一个捕获箭头键...我是node.js的完全新手,所以我可能在这里做一些搞笑的愚蠢.

var stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');

stdin.on('data', function(key){
    if (key === '39') {
        process.stdout.write('right'); 
    }
    if (key === 39) {
        process.stdout.write('right'); 
    }
    if (key == '39') {
            process.stdout.write('right'); 
    }
    if (key == 39) {
        process.stdout.write('right'); 
    }

    if (key == '\u0003') { process.exit(); }    // ctrl-c
});
Run Code Online (Sandbox Code Playgroud)

谢谢.

use*_*109 20

您可以使用按键包.尝试页面上给出的示例.

var keypress = require('keypress');

// make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);

// listen for the "keypress" event
process.stdin.on('keypress', function (ch, key) {
  console.log('got "keypress"', key);
  if (key && key.ctrl && key.name == 'c') {
    process.stdin.pause();
  }
});

process.stdin.setRawMode(true);
process.stdin.resume();
Run Code Online (Sandbox Code Playgroud)

您可以按顺序获得箭头键的UTF-8值.

> process.stdin.resume();got "keypress" { name: 'up',
  ctrl: false,
  meta: false,
  shift: false,
  sequence: '\u001b[A',
  code: '[A' }
> got "keypress" { name: 'down',
  ctrl: false,
  meta: false,
  shift: false,
  sequence: '\u001b[B',
  code: '[B' }
got "keypress" { name: 'right',
  ctrl: false,
  meta: false,
  shift: false,
  sequence: '\u001b[C',
  code: '[C' }
got "keypress" { name: 'left',
  ctrl: false,
  meta: false,
  shift: false,
  sequence: '\u001b[D',
  code: '[D' }
Run Code Online (Sandbox Code Playgroud)


Moe*_*ler 12

这应该可以解决您的问题:

var stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');

stdin.on('data', function(key){
    if (key == '\u001B\u005B\u0041') {
        process.stdout.write('up'); 
    }
    if (key == '\u001B\u005B\u0043') {
        process.stdout.write('right'); 
    }
    if (key == '\u001B\u005B\u0042') {
        process.stdout.write('down'); 
    }
    if (key == '\u001B\u005B\u0044') {
        process.stdout.write('left'); 
    }

    if (key == '\u0003') { process.exit(); }    // ctrl-c
});
Run Code Online (Sandbox Code Playgroud)

这也可能对您有意义:

stdin.on('data', function(key){
    console.log(toUnicode(key)); //Gives you the unicode of the pressed key
    if (key == '\u0003') { process.exit(); }    // ctrl-c
});

function toUnicode(theString) {
  var unicodeString = '';
  for (var i=0; i < theString.length; i++) {
    var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
    while (theUnicode.length < 4) {
      theUnicode = '0' + theUnicode;
    }
    theUnicode = '\\u' + theUnicode;
    unicodeString += theUnicode;
  }
  return unicodeString;
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了这个函数:http: //buildingonmud.blogspot.de/2009/06/convert-string-to-unicode-in-javascript.html