nodejs how to read keystrokes from stdin

前端 未结 6 1821
忘掉有多难
忘掉有多难 2020-11-28 01:37

Is it possible to listen for incoming keystrokes in a running nodejs script? If I use process.openStdin() and listen to its \'data\' event then the

6条回答
  •  醉话见心
    2020-11-28 02:05

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

提交回复
热议问题