使用按键在node.js中启动操作

我正在使用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); }); } 

而不是延迟,我想激活使用按键发送消息。 类似下面的function。

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

您可以将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)) 

它会拒绝任何不是Ctrl-B的击键,但是如果你不想要这样的行为(并且只想等待第一个Ctrl-B) ,那么这个代码是很容易修改的。

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

编辑 :如在评论中@ mh-cbon所build议的,更好的解决scheme可能是使用keypress模块。

试试这个。 如上所述,使用按键使其非常简单。 代码中的key对象告诉你是否按下了ctrlshift ,以及按下的字符。 不幸的是, keypress似乎不处理数字或特殊字符。

 var keypress = require('keypress'); keypress(process.stdin); process.stdin.on('keypress', function (ch, key) { console.log("here's the key object", key); shouldExit(key); if (key) { sendMessage(key); } }); function shouldExit(key) { if (key && key.ctrl && key.name == 'c') { process.stdin.pause(); } } function sendMessage(key) { switch(key.name) { case 'a'; console.log('you typed a'); break; case 'b'; console.log('you typed b'); break; default: console.log('bob is cool'); } } 

当然,在这里的sendMessage()函数中,您可以轻松地用其他更复杂的日志语句replace,进行一些asynchronous调用,调用其他某个函数。 process.stdin.pause()在这里导致程序在ctrl-c上退出,否则程序会继续运行,阻塞你的中断信号,你必须通过命令行手动终止进程。