Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

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?

like image 447
ivanesi Avatar asked Oct 20 '14 07:10

ivanesi


People also ask

What does process stdin on do?

The process. stdin property is an inbuilt application programming interface of the process module which listens for the user input. The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.

How do I use JavaScript stdin?

var a = readline(); the value which you give input will be stored in variable a. readline() : Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript.

How do I end a stdin process?

Simple use of stdin and stdout We can stop the running process in our terminal by pressing ctrl + c .

What is process stdin resume () JavaScript?

process. stdin. resume() A Readable Stream that points to a standard input stream (stdin). Standard input streams are paused by default, so you must call process.


1 Answers

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', ...).

like image 52
c.P.u1 Avatar answered Oct 21 '22 13:10

c.P.u1