如何在node.js中捕获箭头键 [英] How to capture the arrow keys in node.js

查看:114
本文介绍了如何在node.js中捕获箭头键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the utf8 code for all four arrow keys (up down left right)?

我正在学习node.js,并且试图检测何时按下了这些键.

I am learning node.js and I am trying to detect whenever these keys are being pressed.

这是我的工作,但是没有一个捕获箭头键...我是node.js的新手,所以我在这里可能做得很愚蠢.

Here is what I did, but none of it capturing the arrow keys... I am a complete newbie to node.js so I might be doing something hilariously stupid here.

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
});

谢谢.

推荐答案

您可以使用 keypress 程序包.尝试页面上给出的示例.

You can use keypress package. Trying the example given on the page.

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();

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

You get the UTF-8 values of arrow keys at sequence.

> 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' }

这篇关于如何在node.js中捕获箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆