programing

nodejststdin에서 키 입력을 읽는 방법

cafebook 2023. 9. 10. 12:38
반응형

nodejststdin에서 키 입력을 읽는 방법

실행 중인 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를 찾고 있습니다.

가능한가요?

이 기능이 제거되었기 때문에 이 답변을 찾은 사람들을 위해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 );
});

꽤 간단합니다 - 기본적으로 프로세스.stdin의 문서와 같지만 사용합니다.setRawMode( true )문서에서 식별하기 어려운 원시 스트림을 얻을 수 있습니다.

>= v6.1.0 노드에서:

const readline = require('readline');

readline.emitKeypressEvents(process.stdin);

if (process.stdin.setRawMode != null) {
  process.stdin.setRawMode(true);
}

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

https://github.com/nodejs/node/issues/6626 참조

원시 모드로 전환하면 다음과 같은 방법으로 달성할 수 있습니다.

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

이 버전은 keypress 모듈을 사용하며 node.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();

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

이렇게 하면 각 키 누름이 출력됩니다.원하는 코드로 console.log를 변경합니다.

process.stdin.setRawMode(true).setEncoding('utf8').resume().on('data',k=>console.log(k))

댄 헤버든의 대답을 바탕으로 비동기 함수를 제시합니다.

async function getKeypress() {
  return new Promise(resolve => {
    var stdin = process.stdin
    stdin.setRawMode(true) // so get each keypress
    stdin.resume() // resume stdin in the parent process
    stdin.once('data', onData) // like on but removes listener also
    function onData(buffer) {
      stdin.setRawMode(false)
      resolve(buffer.toString())
    }
  })
}

이렇게 쓰임 -

console.log("Press a key...")
const key = await getKeypress()
console.log(key)
if(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

반응형