nodejs как читать нажатия клавиш из stdin

можно ли прослушивать входящие нажатия клавиш в запущенном скрипте nodejs? Если я использую process.openStdin() и слушать ее 'data' событие затем вход буферизуется до следующей новой строки, например:

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

запустив это, я получаю:

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

что я хотел бы видеть:

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

Я ищу эквивалент nodejs, например,getc в ruby

это возможно?

6 ответов


вы можете достичь этого таким образом, если вы переключитесь в режим 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();
});

для тех, кто находит этот ответ, так как эта возможность была лишена tty, вот как получить необработанный поток символов из stdin:

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

довольно просто-в основном так же, как


эта версия использует нажатие модуль и поддерживает узел.в JS версии 0.10, 0.8 и 0.6, а также iojs 2.3. Обязательно запустите 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();

в узле >= 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)
})

см.https://github.com/nodejs/node/issues/6626


С проверенным nodejs 0.6.4 (тест не удался в версии 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);

если вы запустите его и:

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

важный код #1:

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

важный код #2:

.createInterface( process.stdin, {} );

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...);
}