nodejs如何从标准输入读取击键 [英] nodejs how to read keystrokes from stdin

查看:83
本文介绍了nodejs如何从标准输入读取击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在正在运行的 nodejs 脚本中监听传入的击键?如果我使用 process.openStdin() 并监听它的 'data' 事件,那么输入会被缓冲直到下一个换行符,就像这样:

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 input is buffered until the next newline, like so:

// stdin_test.js
var stdin = process.openStdin();
stdin.on('data', function(chunk) { console.log("Got chunk: " + chunk); });

运行这个,我得到:

$ node stdin_test.js
                <-- type '1'
                <-- type '2'
                <-- hit enter
Got chunk: 12

我想看到的是:

$ node stdin_test.js
                <-- type '1' (without hitting enter yet)
 Got chunk: 1

我正在寻找一个相当于例如 getc 在 ruby​​ 中

I'm looking for a nodejs equivalent to, e.g., getc in ruby

这可能吗?

推荐答案

可以这样实现,如果切换到raw模式:

var stdin = process.openStdin(); 
require('tty').setRawMode(true);    

stdin.on('keypress', function (chunk, key) {
  process.stdout.write('Get Chunk: ' + chunk + '
');
  if (key && key.ctrl && key.name == 'c') process.exit();
});

这篇关于nodejs如何从标准输入读取击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆