是否可以在正在运行的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
这可能吗?
答案 0 :(得分:117)
对于那些找到这个答案的人,因为这个功能是从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's documentation一样,但使用setRawMode( true )
来获取原始流,这在文档中很难识别。
答案 1 :(得分:58)
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();
});
答案 2 :(得分:32)
在节点&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)
})
答案 3 :(得分:27)
此版本使用keypress模块并支持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();
答案 4 :(得分:8)
测试了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, {} );
答案 5 :(得分:2)
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...);
}
答案 6 :(得分:0)
基于 Dan Heberden 的回答,这里有一个异步函数 -
async function getKeypress() {
return new Promise(resolve => {
var stdin = process.stdin
stdin.setRawMode(true) // so get each keypress
stdin.resume() // resume stdin in the parent process
stdin.once('data', onData) // like on but removes listener also
function onData(buffer) {
stdin.setRawMode(false)
resolve(buffer.toString())
}
})
}
像这样使用 -
console.log("Press a key...")
const key = await getKeypress()
console.log(key)