如何使用nodejs从stdin读取值

问题描述 投票:1回答:1

我正在尝试从标准输入读取test casevalue然后我将从标准输入读取不同的N值。例如:

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

这是我第一次使用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);
          })
      }

  })

当我测试代码时,我得到了这个:

3
1
N:  1
N:  1
N:  1

它只读取N的一个值,我不能输入2个不同的值,然后显示N = 13次。如何根据测试用例的数量修复N来读取N的不同值?

javascript node.js readline
1个回答
2
投票

每次你rl.on()你创建一个新的事件监听器。因此,当您在循环中执行此操作时,最终会有多个侦听器等待并对输入作出反应。您需要一个能够理解状态并执行所需操作的事件处理程序。例如,要将第一行作为输入数量,读取该输入数量并将其打印出来,您可能会执行以下操作:

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

})
© www.soinside.com 2019 - 2024. All rights reserved.