Search code examples
javascriptnode.jsreadline

How to read a value from stdin using nodejs


I'm trying to read test casevalue from stdin and then I will read a different N value from stdin. E.g:

If T = 3
I could have N = 200, N = 152, N = 35263

It's the first time I work with readline:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });


  rl.on('line', (line) => {
      for (let i = 0; i < line; i++) {
          rl.on('line', (N) => {
              console.log('N: ', N);
          })
      }

  })

When I test the code I got this:

3
1
N:  1
N:  1
N:  1

It read only one value of N and I can't enter the 2 different values then it displays the N = 13 times. How can I fix that to read the different value of N according to the number of test cases?


Solution

  • Every time you rl.on() you create a new event listener. So when you do it in the loop, you end up with multiple listeners all waiting for and reacting to input. You need one event handler that can understand the state and do what you want. For example to take the first line as the number of inputs, read that number of input, and print them out, you might do something like:

    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
    
    let n, res = []; // app state
    
    rl.on('line', (line) => {  // only ONE event listener
        if (n === undefined) { // first input sets n
          n = line
          return
        }
        res.push(line)         // push until you have n items
        if (res.length >= n){
           rl.close()         // done
           console.log("results: ", res)
        }
    
    })