我正在创建一个程序,从命令行输入两个数字,然后在 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();
});
这个程序只显示“请输入第一个数字”,当我输入像 5 这样的数字时,第二次输入也需要 5 并显示答案 10
它根本不问第二个问题。请检查一下并告诉我有什么问题。如果有更好的方法来获取多个输入,请告诉我们。
我是node.js的新手
最佳答案
嵌套代码/回调很难阅读和维护,这是使用 Promise 提出多个问题的更优雅的方式
Node 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()
关于javascript - 如何使用 node.js 的 readline 模块进行两次连续输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36540996/