Javascript 如何使用node.js的readline模块获取两个连续输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36540996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:12:31  来源:igfitidea点击:

How to take two consecutive input with the readline module of node.js?

javascriptnode.jsreadline

提问by Puneet Singh

I am creating a program to take input of two numbers from the command line and then showing there sum in node.js. I am using readline module to take stdin. Below is my code.

我正在创建一个程序来从命令行输入两个数字,然后在 node.js 中显示总和。我正在使用 readline 模块来获取标准输入。下面是我的代码。

const readline = require('readline');

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

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

rl.question('Please enter the first number', (answer1) => {
    r2.question('Please enter the second number', (answer2) => {
        var result = (+answer1) + (+answer2);
        console.log(`The sum of above two numbers is ${result}`);
    });
    rl.close();
});

This program just show me "Please enter the first number" and when i enter a number like 5, it takes 5 for second input also and shows the answer 10

这个程序只显示“请输入第一个数字”,当我输入像 5 这样的数字时,第二次输入也需要 5 并显示答案 10

It don't ask second question at all. Please check this and tell me what is the problem. And if there is any better way to take multiple input please tell that.

它根本不问第二个问题。请检查这个并告诉我是什么问题。如果有更好的方法来接受多个输入,请告诉。

I am a novice user in node.js

我是 node.js 的新手用户

回答by jc1

Nested code/callback are terrible to read and maintain, here's a more elegant way to use Promise for asking multiple questions

嵌套代码/回调很难阅读和维护,这是使用 Promise 询问多个问题的更优雅的方法

node 8+

节点 8+

'use strict'

const readline = require('readline')

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

const question1 = () => {
  return new Promise((resolve, reject) => {
    rl.question('q1 What do you think of Node.js? ', (answer) => {
      console.log(`Thank you for your valuable feedback: ${answer}`)
      resolve()
    })
  })
}

const question2 = () => {
  return new Promise((resolve, reject) => {
    rl.question('q2 What do you think of Node.js? ', (answer) => {
      console.log(`Thank you for your valuable feedback: ${answer}`)
      resolve()
    })
  })
}

const main = async () => {
  await question1()
  await question2()
  rl.close()
}

main()

回答by Thamilan

No need another variable, just use like this:

不需要另一个变量,只需像这样使用:

const readline = require('readline');

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

rl.question('Please enter the first number : ', (answer1) => {
    rl.question('Please enter the second number : ', (answer2) => {
        var result = (+answer1) + (+answer2);
        console.log(`The sum of above two numbers is ${result}`);
        rl.close();
    });
});

回答by user3032538

I would ask the questions in an async function and wrap readline similarly to how Jason did it above. Although with slightly less code :)

我会在 async 函数中提出问题,并以类似于上面 Jason 的方式包装 readline。虽然代码略少:)

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

function question(theQuestion) {
    return new Promise(resolve => rl.question(theQuestion, answ => resolve(answ)))
}

async function askQuestions(){
    var answer = await question("A great question")
    console.log(answer);
}

回答by Jason

For those interested I put together this little module that takes an array of questions and returns a promise that resolves to an array of answers:

对于那些感兴趣的人,我将这个小模块放在一起,它接受一系列问题并返回一个可解析为一系列答案的承诺:

const readline = require('readline');

const AskQuestion = (rl, question) => {
    return new Promise(resolve => {
        rl.question(question, (answer) => {
            resolve(answer);
        });
    });
}

const Ask = function(questions) {
    return new Promise(async resolve => {
        let rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });

        let results = [];
        for(let i=0;i < questions.length;i++) {
            const result = await AskQuestion(rl, questions[i]);
            results.push(result);
        }
        rl.close();
        resolve(results);
    })
}

module.exports = {
    askQuestions: Ask 
}

Save that in a file called ask.js (or whatever you like) and use like this:

将其保存在名为 ask.js(或任何您喜欢的文件)的文件中,然后像这样使用:

const { askQuestions } = require('./ask');

askQuestions([
   'What is question 1?',
   'What is question 2?',
   'What is question 3?'
])
    .then(answers => {
        // Do whatever you like with the array of answers
    });

Note: Will need a transpiler or recent version of Node as it uses a lot of ES6 features.

注意:需要一个转译器或最新版本的 Node,因为它使用了很多 ES6 特性。

回答by serious_luffy

you could use recursion :

你可以使用递归:

var fs = require('fs')
var readline = require('readline')


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

 var keys = []
function gen(rank){
  if(rank > 3)
    {
        //do whatever u want
        var sum_avg = 0
        for (i in keys)
             {
                sum_avg+=Number(keys[i])
             }
         console.log(sum_avg/3); 
         return -1;     
    }
    else 
    { 
        var place = rank>1 ? "th" : "st"
        var total = rank+place 
        rl.question("Please enter the "+total+ " number :",function(answer){
            keys.push(answer)
            //this is where the recursion works
             gen(rank+1)
        })
     }
  }

//pass the value from where you want to start
  gen(1)