node js 写按键精灵
I find the stuff that people are doing with Node.js incredibly interesting. You here about people using Node.js to control drones, Arduinos, and a host of other devices. I took advantage of Node.js to create a Roku Remote, a project that was fun and easier than I thought it would be. There was one piece of this experiment that was difficult, however: listening for keystrokes within the same shell that executed the script.
我发现人们使用Node.js所做的事情非常有趣。 在这里,您可以了解使用Node.js来控制无人机,Arduino和许多其他设备的人们。 我利用Node.js创建了一个Roku Remote ,这个项目比我想象的要有趣和容易。 但是,该实验中有一个很困难:在执行脚本的同一shell中侦听击键。
The process for using the remote is as follows:
使用遥控器的过程如下:
Execute the script to connect to your Roku: node remote
执行脚本以连接到Roku: node remote
In the same shell, use arrow keys and hot keys to navigate the Roku 在同一外壳中,使用箭头键和热键导航RokuPress CONTROL+C to kill the script
按CONTROL+C取消脚本
The following JavaScript code is what I needed to use to both listen for keystrokes within the same shell once the script had been started:
脚本启动后,我需要使用以下JavaScript代码来侦听同一外壳中的击键:
// Readline lets us tap into the process events const readline = require('readline'); // Allows us to listen for events from stdin readline.emitKeypressEvents(process.stdin); // Raw mode gets rid of standard keypress events and other // functionality Node.js adds by default process.stdin.setRawMode(true); // Start the keypress listener for the process process.stdin.on('keypress', (str, key) => { // "Raw" mode so we must do our own kill switch if(key.sequence === '\u0003') { process.exit(); } // User has triggered a keypress, now do whatever we want! // ... });The code above turns your Node.js script into an active wire for listening to keypress events. With my Roku Remote, I pass arrow and letter keypress events directly to the Roku via a REST API (full code here). I love that Node.js made this so easy -- another reason JavaScript always wins!
上面的代码将您的Node.js脚本变成了一个活跃的线路,用于监听按键事件。 使用Roku Remote,我通过REST API( 此处为完整代码 )将箭头和字母按键事件直接传递给Roku。 我喜欢Node.js使其变得如此简单-JavaScript永远赢的另一个原因!
翻译自: https://davidwalsh.name/node-raw-mode
node js 写按键精灵