how to work with “process.stdin.on”?

落爺英雄遲暮 提交于 2019-12-13 12:59:32

问题


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.

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?


回答1:


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

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




回答2:


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

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.



来源:https://stackoverflow.com/questions/26460324/how-to-work-with-process-stdin-on

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!