如何使用节点和 JavaScript 在按 Enter 之前从终端读取用户输入?
如何使用节点和 JavaScript 在按 Enter 之前从终端读取用户输入?
我制作了一个简单的 javascript 应用程序,它使用 process.stdin 或 readline 来获取用户输入,但我不希望用户必须使用 Enter/Return 提交输入。我想读取按键/按键上的用户输入。这可能吗?我怎样才能做到这一点?谢谢!
要求:
- javascript、节点
- 来自终端用户的
- 不需要通过 Enter/Return 提交字符串
首选:
- 更少的库,更多的普通 javascript
- 处理任何键:字母、数字、箭头键、修饰符
How to read user input from terminal before pressing enter using node and javascript?
I have made a simple javascript application which uses process.stdin or readline to get user input, but I don't want the user to have to submit their input with enter/return. I'd like to read user input on keydown/keypress. Is this possible? How might I accomplish this? Thanks!
Requirements:
- javascript, node
- from terminal
- user not required to submit string with enter/return
Prefer:
- less libraries, more vanilla javascript
- handles any key: letters, numbers, arrow keys, modifiers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种简单的方法是使用
iohook
包。Node.JS 的原生方式是这样的。
第一行
require("readline").emitKeypressEvents(process.stdin)
使process.stdin
发出按键事件,因为它通常不发出该事件。第二个
process.stdin.setRawMode(true)
使process.stdin
成为原始设备。在原始设备配置的流中,按键事件是按字符发出的,而不是按回车键发出的。然后,将
keypress
事件侦听器添加到process.stdin
中以处理按键。注意
当
process.stdin
转换为原始设备时,Ctrl+C
不会发出SIGINT
信号,换句话说,Ctrl+C
不会停止程序。这意味着您需要手动绑定一个键才能退出。An easy way to do it could be with the
iohook
package.The native Node.JS way to do it would be like this.
The first line,
require("readline").emitKeypressEvents(process.stdin)
makesprocess.stdin
emit keypress events, as it normally does not emit the event.The second,
process.stdin.setRawMode(true)
makesprocess.stdin
a raw device. In a raw device configured stream, key press events are emitted on a per character basis, instead of emitting per enter key press.Then, the
keypress
event listener is added ontoprocess.stdin
to handle keypresses.Note
When
process.stdin
is converted to a raw device,Ctrl+C
does not emit aSIGINT
signal, in other words,Ctrl+C
will not stop the program. This means that you will need to manually bind a key to exit.这就是我在节点 16.20.1 上的工作:
This was what worked for me on node 16.20.1: