从nodejs的控制台中反复获取用户输入?

时间:2019-09-15 15:57:00

标签: javascript node.js

如何循环从控制台获取输入?

让我们假设节点promt询问班上有多少学生? 在该用户输入5后,应该提示5次“一个一个地输入他们的名字”, 并且所有名称都必须存储在数组中

2 个答案:

答案 0 :(得分:1)

您可以使用readline-sync软件包

 var readline = require('readline-sync');

    let num = readline.question("how many students are in a class ?");
    let names=[];
    for(let i=0;i<=num;i++)
    {
      let name = readline.question("Enter Name?");
      names.push(name);
    }
    console.log(names);

工作代表-https://repl.it/repls/LightyellowEvenBusinesses

答案 1 :(得分:1)

尝试一下

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

let n;
let array = []

function mainfunction() {
    if( n == array.length){
        console.log("your output: ",  array)
        rl.close()
    }
    else{
        rl.question('enter student name one by one \n', (name) => {
            array.push(name)
            mainfunction()
        })
    }
 }

rl.question('enter the number of students ', (answer) => {
    n = answer
    mainfunction()
});