nodejs jak odczytać naciśnięcia klawiszy ze stdin

Czy możliwe jest nasłuchiwanie przychodzących naciśnięć klawiszy w uruchomionym skrypcie nodejs? Jeśli użyję process.openStdin() i odsłucham jego Zdarzenie 'data' wtedy wejście jest buforowane aż do następnego znaku nowej linii, tak:

// stdin_test.js
var stdin = process.openStdin();
stdin.on('data', function(chunk) { console.log("Got chunk: " + chunk); });

Uruchamiając to, dostaję:

$ node stdin_test.js
                <-- type '1'
                <-- type '2'
                <-- hit enter
Got chunk: 12

Chciałbym zobaczyć:

$ node stdin_test.js
                <-- type '1' (without hitting enter yet)
 Got chunk: 1

Szukam nodejsa równoważnego np., getc w ruby

Czy to możliwe?
Author: bantic, 2011-02-15

6 answers

Możesz to osiągnąć w ten sposób, jeśli przełączysz się na tryb raw:

var stdin = process.openStdin(); 
require('tty').setRawMode(true);    

stdin.on('keypress', function (chunk, key) {
  process.stdout.write('Get Chunk: ' + chunk + '\n');
  if (key && key.ctrl && key.name == 'c') process.exit();
});
 52
Author: DanS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-13 16:51:46

Dla tych, którzy znaleźli tę odpowiedź, ponieważ ta funkcja została usunięta z tty, Oto jak uzyskać surowy strumień znaków ze standardowego wejścia:

var stdin = process.stdin;

// without this, we would only get streams once enter is pressed
stdin.setRawMode( true );

// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();

// i don't want binary, do you?
stdin.setEncoding( 'utf8' );

// on any data into stdin
stdin.on( 'data', function( key ){
  // ctrl-c ( end of text )
  if ( key === '\u0003' ) {
    process.exit();
  }
  // write the key to stdout all normal like
  process.stdout.write( key );
});

Dość proste - w zasadzie tak jak proces.dokumentacja stdin , ale używając setRawMode( true ) do uzyskania strumienia raw, który jest trudniejszy do zidentyfikowania w dokumentacji.

 108
Author: Dan Heberden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-20 05:38:15

Ta wersja używa modułu klawiatura i obsługuje węzeł.js w wersji 0.10, 0.8 i 0.6 oraz iojs 2.3. Pamiętaj, aby uruchomić npm install --save keypress.

var keypress = require('keypress')
  , tty = require('tty');

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

if (typeof process.stdin.setRawMode == 'function') {
  process.stdin.setRawMode(true);
} else {
  tty.setRawMode(true);
}
process.stdin.resume();
 24
Author: Peter Lyons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-26 00:00:52

In node > = v6. 1. 0:

const readline = require('readline');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  console.log(str)
  console.log(key)
})

Zobacz https://github.com/nodejs/node/issues/6626

 23
Author: arve0,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-03 20:10:12

With NodeJS 0.6.4 tested ( Test nie powiódł się w wersji 0.8.14):

rint = require('readline').createInterface( process.stdin, {} ); 
rint.input.on('keypress',function( char, key) {
    //console.log(key);
    if( key == undefined ) {
        process.stdout.write('{'+char+'}')
    } else {
        if( key.name == 'escape' ) {
            process.exit();
        }
        process.stdout.write('['+key.name+']');
    }

}); 
require('tty').setRawMode(true);
setTimeout(process.exit, 10000);

If you run it and:

  <--type '1'
{1}
  <--type 'a'
{1}[a]

Ważny kod #1:

require('tty').setRawMode( true );

Ważny kod #2:

.createInterface( process.stdin, {} );
 8
Author: befzz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-22 17:27:56
if(Boolean(process.stdout.isTTY)){
  process.stdin.on("readable",function(){
    var chunk = process.stdin.read();
    if(chunk != null)
      doSomethingWithInput(chunk);
  });
  process.stdin.setRawMode(true);
} else {
  console.log("You are not using a tty device...);
}
 2
Author: Xenon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-05 14:45:57