'Cannot distinguish between up/down arrow in stdin raw mode

I have this bit of code:

  process.stdin.setRawMode(true).resume();

  process.stdin.on('data', (buf) => {

    const str = String(buf);
    const charAsAscii = String(buf.toString().charCodeAt(0));

    switch (charAsAscii) {

      case '25': // left arrow ?
        console.log('left arrow');
        return;

      case '26': // right arrow ?
        console.log('right arrow');
        return;

      case '27': // down arrow
        console.log('down arrow');
        return;

      case '28': // up arrow?
        console.log('up arrow');
        return;

      default:
        console.error('default')
    }

}

all the arrow keys seem to be recognized as up arrow, that is, all 4 arrow keys always match case '28' ... I am looking to distinguish between up/down/left/right arrow keys, anyone know how to do this?



Solution 1:[1]

For arrow keys, buffer is a bit different : there are 3 bytes. I have no idea what they represent, but i just know you have to get the third char :

process.stdin.setRawMode(true)
process.stdin.on('data', (data) => {
    const str = data.toString();
    if (str.length == 3) {
        console.log(str.charCodeAt(2))
    }
})

Arrow codes :

Up -> 65
Down -> 66
Right -> 67
Left -> 68

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Du Couscous