是否可以在运行的 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
我正在寻找一个相当于的nodejs,例如getc in ruby
这可能吗?
对于那些找到这个答案的人来说,因为这个功能被剥夺了tty
,以下是如何从 stdin 获取原始字符流:
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 的文档但使用setRawMode( true )
获取原始流,这在文档中很难识别。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)