如何使用“process.stdin.on"? [英] how to work with "process.stdin.on"?

查看:218
本文介绍了如何使用“process.stdin.on"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 process.stdin.

I'm trying to understand process.stdin.

例如 - 我需要在控制台中显示数组元素.我应该允许用户选择将显示哪个元素.

For example - I need to show array elements in console. And i should allow user choose which element will be shown.

我有代码:

var arr = ['elem1','elem2','elem3','elem4','elem5'],
    lastIndx = arr.length-1;

showArrElem();

function showArrElem () {

  console.log('press number from 0 to ' + lastIndx +', or "q" to quit');

  process.stdin.on('readable', function (key) {
        var key = process.stdin.read();
        if (!process.stdin.isRaw) {
          process.stdin.setRawMode( true );
        } else {
          var i = String(key);
          if (i == 'q') {
            process.exit(0);
          } else {
            console.log('you press ' +i); // null
            console.log('e: ' +arr[i]);
            showArrElem();
          };
        };  
  });

};

为什么我第二次输入数字时i"为空?如何正确使用process.stdin.on"?

Why the "i" is null when i type number a second time? How to use "process.stdin.on" correctly?

推荐答案

您在每个输入字符之后在 process.stdin 上附加一个 readable 侦听器,这导致process.stdin.read() 为每个字符调用多次.stream.Readable.read()process.stdin 的一个实例,如果输入缓冲区中没有数据,则返回 null.要解决此问题,请附加一次侦听器.

You're attaching a readable listener on process.stdin after every input character, which is causing process.stdin.read() to be invoked more than one time for each character. stream.Readable.read(), which process.stdin is an instance of, returns null if there's no data in the input buffer. To work around this, attach the listener once.

process.stdin.setRawMode(true);
process.stdin.on('readable', function () {
  var key = String(process.stdin.read());
  showArrEl(key);
});

function showArrEl (key) {
  console.log(arr[key]);
}

或者,您可以使用 process.stdin.once('readable', ...) 附加一次性侦听器.

Alternatively, you can attach a one-time listener using process.stdin.once('readable', ...).

这篇关于如何使用“process.stdin.on"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆