node.js 如何使用“process.stdin.on”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26460324/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:01:17  来源:igfitidea点击:

how to work with "process.stdin.on"?

node.jsstdin

提问by ivanesi

I'm trying to understand process.stdin.

我正在尝试了解 process.stdin。

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

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

I have code:

我有代码:

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

};

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

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

采纳答案by c.P.u1

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

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

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

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

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

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

回答by brian hague

This is typically how I get input when using stdin (node.js) This is the ES5 version, I don't use ES6 yet.

这通常是我在使用 stdin (node.js) 时获取输入的方式 这是 ES5 版本,我还没有使用 ES6。

function processThis(input) {
  console.log(input);  //your code goes here
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
  _input += input;
});

process.stdin.on("end", function () {
   processThis(_input);
});

hope this helps.

希望这可以帮助。