node.js – how to work with process.stdin.on?

node.js – how to work with process.stdin.on?

Youre 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 theres 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, ...).

This is typically how I get input when using stdin (node.js) This is the ES5 version, I dont 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.

node.js – how to work with process.stdin.on?

Leave a Reply

Your email address will not be published.