How to capture the arrow keys in node.js
node.js, utf-8
Solution
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();
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' }
Problem
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.