如何使用node.js的readline模块进行两个连续的输入? [英] How to take two consecutive input with the readline module of node.js?

查看:53
本文介绍了如何使用node.js的readline模块进行两个连续的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

该程序只显示请输入第一个数字",当我输入5之类的数字时,第二个输入也要输入5,并显示答案10

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

它根本不问第二个问题.请检查并告诉我是什么问题.如果有更好的方法来进行多次输入,请告诉我们.

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.

我是node.js的新手

I am a novice user in node.js

推荐答案

嵌套的代码/回调很容易阅读和维护,这是使用Promise提出多个问题的一种更优雅的方式

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

节点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()

这篇关于如何使用node.js的readline模块进行两个连续的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆