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

I am trying to understand process.stdin.

For example, I need to show array elements in the console. And I have to let the user choose which item will be shown.

I have a 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 is "i" null when I dial a second time? How to use "process.stdin.on"?

+4
source share
2 answers

You attach the readable listener to process.stdin after each input character that calls process.stdin.read() to be called more than once for each character. stream.Readable.read() , which process.stdin is an instance of, returns null if there is no data in the input buffer. To get 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 connect a one-time listener using process.stdin.once('readable', ...) .

+5
source

Typically, I get input when using stdin (node.js). This is a version of ES5, while I am not using 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.

+1
source

Source: https://habr.com/ru/post/1262815/


All Articles