How to capture the arrow keys in node.js

前端 未结 5 1136
南旧
南旧 2020-12-29 05:57

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

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

He

5条回答
  •  伪装坚强ぢ
    2020-12-29 06:46

    This should solve your problem:

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

    This could also be of interest for you:

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

    I found the function here: http://buildingonmud.blogspot.de/2009/06/convert-string-to-unicode-in-javascript.html

提交回复
热议问题