Input nodejs如何从stdin读取击键

Input nodejs如何从stdin读取击键,input,node.js,stdin,Input,Node.js,Stdin,是否可以在运行的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

是否可以在运行的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\u test.js
如果切换到原始模式,可以通过以下方式实现:
测试nodejs 0.6.4时(在0.8.14版中测试失败):

rint=require('readline').createInterface(process.stdin,{});
打印输入打开('keypress',函数(字符,键){
//控制台日志(键);
如果(键==未定义){
process.stdout.write('{'+char+'}'))
}否则{
如果(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]
重要代码#2:

此版本使用模块,支持node.js版本0.10、0.8和0.6以及iojs 2.3。确保运行
npm安装--保存按键

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

对于那些从
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 );
});
非常简单-基本上与使用
setRawMode(true)
获取原始流类似,但在文档中很难识别原始流。

在node>=v6.1.0中:

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...);
}
const readline = require('readline');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  console.log(str)
  console.log(key)
})

参见

别担心,我发现了我自己,
process.stdin.resume();process.stdin.on('data',function(chunk){process.stdout.write('data:'+chunk);})
setRawMode
移动到
openStdin()
的下方,因为只有初始化
stdin
时才能设置模式。stdin似乎不再发出按键事件,而是发出具有不同参数的数据事件。嗯,是的。实际上,
stdin.on('keypress',function(chunk,key))
在最近的版本中已被删除。我敢肯定,
openStdin()
已经被删除或弃用。现在,您可以通过
进程访问stdin。stdin
这个答案不再有用。因为Node.js API有点变化。在下面找到正确答案。谢谢。。它很简单,而且很容易立即实现:)正是我想要的。与Node.js 0.8+不兼容。您必须导入“按键”。请看Peter Lyons的回答。这确实适用于0.8,但有趣的是,它是一个不断变化的api。应该使用key='\u0003'(双精度而不是三重等号)来让它工作有没有办法让这个写上、下、左、右键也工作?这在节点v0.10.25上不起作用,它说使用
process.stdin.setRawMode()
相反,这会出错,并表示没有方法setRawMode,非常annoying@Plentybinary我怀疑您实际上没有运行节点v0.10.25。我对v0.10.25进行了测试,它工作正常。和
process.stdin.setRawMode
存在,是一个函数,工作正常。我也在iojs-2.3.1上进行了测试,它仍然在那里工作。FWIW,它至少在v0.10.40上继续工作,在7上尝试这个,我得到了
process.stdin.setRawMode不是一个函数
。稍后将尝试更深一点。@MattMolnar该函数仅在TTY时存在,因此请检查该函数first@MattMolnar你需要将你的应用程序作为外部终端运行,请参阅(添加此注释以便更容易找到此问题;我花了几天时间找到了合适的词语):这是在输入中发送换行(换行)字符之前,如何逐个字符读取标准输入。
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();
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 );
});
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...);
}
const readline = require('readline');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  console.log(str)
  console.log(key)
})