program tip

nodejs stdin에서 키 입력을 읽는 방법

radiobox 2020. 8. 11. 08:14
반응형

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

이게 가능해?


원시 모드로 전환하면 다음과 같이 할 수 있습니다.

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

매우 간단합니다-기본적으로 process.stdin의 문서와 같지만 문서setRawMode( true ) 에서 식별하기 어려운 원시 스트림을 가져 오는 데 사용 합니다.


노드> = 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)
})

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


This version uses the keypress module and supports node.js version 0.10, 0.8 and 0.6 as well as iojs 2.3. Be sure to run 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();

With nodejs 0.6.4 tested (Test failed in version 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]

Important code #1:

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

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

참고URL : https://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin

반응형