关于input:node.js如何从stdin中读取击键

nodejs how to read keystrokes from stdin

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

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

运行此命令,我得到:

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

我想看的是:

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

我正在寻找与ruby中的getc等价的nodejs

这可能吗?


对于那些因为从tty中剥离了此功能而找到了答案的人,这是从stdin中获取原始字符流的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 )来获取原始流,这在文档中很难识别。


如果您切换到原始模式,则可以通过这种方式实现:

1
2
3
4
5
6
7
8
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();
});


在节点> = v6.1.0中:

1
2
3
4
5
6
7
8
9
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


此版本使用keypress模块??,并支持node.js版本0.10、0.8和0.6以及iojs 2.3。确保运行npm install --save keypress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();


在测试nodejs 0.6.4的情况下(测试在0.8.14版本中失败):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);

如果您运行它并:

1
2
3
4
  <--type '1'
{1}
  <--type 'a'
{1}[a]

重要代码#1:

1
require('tty').setRawMode( true );

重要代码#2:

1
.createInterface( process.stdin, {} );


1
2
3
4
5
6
7
8
9
10
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...);
}