使用keypress在node.js中启动操作

9 javascript stdin keystroke node.js promise

我正在使用node.js v4.5

我写了下面的函数来发送延迟的重复消息.

function send_messages() {
    Promise.resolve()
        .then(() => send_msg() )
        .then(() => Delay(1000) )
        .then(() => send_msg() )
        .then(() => Delay(1000))
        .then(() => send_msg() )        
    ;
}

function Delay(duration) {
    return new Promise((resolve) => {
        setTimeout(() => resolve(), duration);
    });
}
Run Code Online (Sandbox Code Playgroud)

我希望使用按键激活发送消息,而不是延迟.类似下面的功能.

function send_messages_keystroke() {
    Promise.resolve()
        .then(() => send_msg() )
        .then(() => keyPress('ctrl-b') ) //Run subsequent line of code send_msg() if keystroke ctrl-b is pressed
        .then(() => send_msg() )
        .then(() => keyPress('ctrl-b') )
        .then(() => send_msg() )        
    ;
}
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 6

您可以process.stdin使用原始模式访问单个击键.

这是一个独立的例子:

function send_msg(msg) {
  console.log('Message:', msg);
}

// To map the `value` parameter to the required keystroke, see:
// http://academic.evergreen.edu/projects/biophysics/technotes/program/ascii_ctrl.htm
function keyPress(value) {
  return new Promise((resolve, reject) => {
    process.stdin.setRawMode(true);
    process.stdin.once('data', keystroke => {
      process.stdin.setRawMode(false);
      if (keystroke[0] === value) return resolve();
      return reject(Error('invalid keystroke'));
    });
  })
}

Promise.resolve()
  .then(() => send_msg('1'))
  .then(() => keyPress(2))
  .then(() => send_msg('2'))
  .then(() => keyPress(2))
  .then(() => send_msg('done'))
  .catch(e => console.error('Error', e))
Run Code Online (Sandbox Code Playgroud)

它会拒绝任何没有的击键Ctrl-B,但如果你不想要那种行为,那么代码很容易修改(例如,只想等待第一次Ctrl-B).

传递给keyPress的值是键的十进制ASCII值:Ctrl-A是1,Ctrl-B是2,a是97,等等.

编辑:正如@ mh-cbon在评论中所建议的那样,更好的解决方案可能是使用该keypress模块.