是否可以在正在运行的nodejs脚本中侦听传入的击键?如果我使用process.openStdin()
并侦听它的'data'
事件,那么输入将被缓冲到下一个换行符,如下所示:
// 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
in ruby相当的nodejs
这个是可能的吗?
发布于 2011-02-21 04:42:14
如果你切换到raw模式,你可以这样实现:
var stdin = process.openStdin();
require('tty').setRawMode(true);
stdin.on('keypress', function (chunk, key) {
process.stdout.write('Get Chunk: ' + chunk + '\n');
if (key && key.ctrl && key.name == 'c') process.exit();
});
发布于 2012-09-20 13:38:16
对于那些找到这个答案的人来说,因为这个功能是从tty
中剥离出来的,下面是如何从标准输入中获取原始字符流的方法:
var stdin = process.stdin;
// without this, we would only get streams once enter is pressed
stdin.setRawMode( true );
// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();
// i don't want binary, do you?
stdin.setEncoding( 'utf8' );
// on any data into stdin
stdin.on( 'data', function( key ){
// ctrl-c ( end of text )
if ( key === '\u0003' ) {
process.exit();
}
// write the key to stdout all normal like
process.stdout.write( key );
});
非常简单-基本上就像process.stdin's documentation,但使用setRawMode( true )
来获取原始流,这在文档中很难识别。
发布于 2016-05-08 05:19:36
在节点>= v6.1.0中:
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (str, key) => {
console.log(str)
console.log(key)
})
https://stackoverflow.com/questions/5006821
复制相似问题