nodejs如何从标准输入读取击键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5006821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs how to read keystrokes from stdin
提问by bantic
Is it possible to listen for incoming keystrokes in a running nodejs script?
If I use process.openStdin()and listen to its 'data'event then the input is buffered until the next newline, like so:
是否可以在正在运行的 nodejs 脚本中监听传入的击键?如果我使用process.openStdin()并监听它的'data'事件,那么输入被缓冲直到下一个换行符,如下所示:
// stdin_test.js
var stdin = process.openStdin();
stdin.on('data', function(chunk) { console.log("Got chunk: " + chunk); });
Running this, I get:
运行这个,我得到:
$ node stdin_test.js
<-- type '1'
<-- type '2'
<-- hit enter
Got chunk: 12
What I'd like is to see:
我想看到的是:
$ node stdin_test.js
<-- type '1' (without hitting enter yet)
Got chunk: 1
I'm looking for a nodejs equivalent to, e.g., getcin ruby
Is this possible?
这可能吗?
采纳答案by DanS
You can achieve it this way, if you switch to raw mode:
如果切换到原始模式,您可以通过这种方式实现:
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();
});
回答by Dan Heberden
For those finding this answer since this capability was stripped from tty, here's how to get a raw character stream from stdin:
对于那些因为此功能已从 中剥离而找到此答案的人,以下是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 );
});
pretty simple - basically just like process.stdin's documentationbut using setRawMode( true )to get a raw stream, which is harder to identify in the documentation.
非常简单 - 基本上就像process.stdin 的文档一样,但setRawMode( true )用于获取原始流,这在文档中更难识别。
回答by arve0
In node >= v6.1.0:
在节点 >= 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)
})
回答by Peter Lyons
This version uses the keypressmodule and supports node.js version 0.10, 0.8 and 0.6 as well as iojs 2.3. Be sure to run npm install --save keypress.
此版本使用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();
回答by befzz
With nodejs 0.6.4 tested (Test failed in version 0.8.14):
使用 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);
if you run it and:
如果你运行它并且:
<--type '1'
{1}
<--type 'a'
{1}[a]
Important code #1:
重要代码#1:
require('tty').setRawMode( true );
Important code #2:
重要代码#2:
.createInterface( process.stdin, {} );
回答by élektra
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...);
}

