是否可以在运行中侦听传入的击键 的NodeJS </跨度> 脚本?如果我使用process.openStdin()并听取它的’data’事件,那么输入将被缓冲,直到下一个换行符,就像这样’ ‘ &lt; - 类型’2’ &lt; - 命中输入得到了大块:12
我想要看的是:
$ node stdin_test.js &lt; - type’1’(尚未点击进入) 大块:1
我正在寻找一个 的NodeJS </跨度> 相当于例如红宝石中的getc
这可能吗? 鈥
在节点&gt; = 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://github.com/nodejs/node/issues/6626
对于那些找到这个答案的人,因为这个能力被剥夺了 tty ,这是如何从stdin获取原始字符流:
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的文档 但使用 setRawMode( true ) 获取原始流,这在文档中更难识别。
setRawMode( true )
使用nodejs 0.6.4测试( 的 版本0.8.14中的测试失败 强> ):
rint = require('readline').createInterface( process.stdin, {} ); rint.input.on('keypress',function( char, key) { //console.log(key); if( key == undefined ) { process.stdout.write('{'+char+'}') } else { if( key.name == 'escape' ) { process.exit(); } process.stdout.write('['+key.name+']'); } }); require('tty').setRawMode(true); setTimeout(process.exit, 10000);
如果你运行它并:
<--type '1' {1} <--type 'a' {1}[a]
重要代码#1:
require('tty').setRawMode( true );
重要代码#2:
.createInterface( process.stdin, {} );
if(Boolean(process.stdout.isTTY)){ process.stdin.on("readable",function(){ var chunk = process.stdin.read(); if(chunk != null) doSomethingWithInput(chunk); }); process.stdin.setRawMode(true); } else { console.log("You are not using a tty device...); }