nodejs how to read keystrokes from stdin

前端 未结 6 1823
忘掉有多难
忘掉有多难 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:20

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

提交回复
热议问题