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.
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
});
Thanks.
This should solve your problem:
This could also be of interest for you:
I found the function here: http://buildingonmud.blogspot.de/2009/06/convert-string-to-unicode-in-javascript.html
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.:
or
If
yourscript.js
isthen
example
(or the content oftest.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):
I don't know if there is a library that allows user interaction via the console.
You can use keypress package. Trying the example given on the page.
You get the UTF-8 values of arrow keys at sequence.
Assuming you mean the key codes:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
To capture them in JavaScript:
A mix of Moezalez and user568109 answers worked for me: