nodejs如何从标准input读取按键

是否有可能侦听正在运行的nodejs脚本中的传入键击? 如果我使用process.openStdin()并侦听其'data'事件,那么input会被缓冲直到下一个换行符,如下所示:

 // 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相当于,例如, rubygetc

这可能吗?

如果切换到原始模式,可以用这种方法实现:

 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(); }); 

对于那些从tty中剥离tty这个问题的人来说,下面是如何从stdin获取一个原始字符stream的方法:

 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 )来获取原始stream,这在文档中很难识别。

该版本使用按键模块,支持node.js版本0.10,0.8和0.6以及iojs 2.3。 一定要运行npm install --save keypress

 var keypress = require('keypress') , tty = require('tty'); // make `process.stdin` begin emitting "keypress" events keypress(process.stdin); // listen for the "keypress" event process.stdin.on('keypress', function (ch, key) { console.log('got "keypress"', key); if (key && key.ctrl && key.name == 'c') { process.stdin.pause(); } }); if (typeof process.stdin.setRawMode == 'function') { process.stdin.setRawMode(true); } else { tty.setRawMode(true); } process.stdin.resume(); 

在最新的节点(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

使用nodejs 0.6.4testing( testing版本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...); }