如何使用node.js的readline模块连续两次输入?

Pun*_*ngh 12 javascript readline node.js

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

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();
});
Run Code Online (Sandbox Code Playgroud)

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

它根本不问第二个问题.请检查一下,告诉我是什么问题.如果有更好的方法可以采取多种输入,请告诉我们.

我是node.js的初级用户

jc1*_*jc1 20

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

节点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()
Run Code Online (Sandbox Code Playgroud)

  • 不鼓励仅使用代码回答,因为它们不会为未来的读者提供太多信息,请对您所写的内容提供一些解释 (2认同)

Tha*_*lan 16

不需要另一个变量,只需使用如下:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 为什么控制台输入在节点中如此复杂。他们为什么不能使用一行命令。是什么在阻止这种情况? (5认同)

小智 7

我会在 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么从命令行读取输入如此复杂,与任何其他语言不同! (4认同)