How to capture the arrow keys in node.js

前端 未结 5 1166
南旧
南旧 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:36

    I'm a node newbie myself, but AFAIK this can't work like this. Node alone has no "front end" or user interface API which would allow you to capture user input. And functional keys like arrow keys are not sent to "stdin", just keys that produce characters.

    You could read command line arguments or send data to "stdin" via the command line, e.g.:

     echo "example" | node yourscript.js
    

    or

     node yourscript.js < test.txt
    

    If yourscript.js is

    process.stdin.resume();
    
    process.stdin.on('data', function(chunk) {
      console.log('chunk: ' + chunk);
    });
    

    then example (or the content of test.txt) will be echo'd to node's console, but neither will allow you any direct user interaction.

    For a more complex interaction using "stdin" see http://docs.nodejitsu.com/articles/command-line/how-to-prompt-for-command-line-input , however as I said arrow keys aren't sent to "stdin", so you can't capture them.

    Normally you use node for web applications, so you could write your node script as a web server and use a browser as the front end.

    Or you look for libraries/modules that provide a front end. The ones I know of are (I haven't used either):

    • node-gui a GTK+ binding
    • node-webkit an alternative runtime based on Chromium which allows you to write front ends in HTML/CSS/JavaScript.

    I don't know if there is a library that allows user interaction via the console.

提交回复
热议问题