我正在创建一个程序,从命令行接受两个数字的输入,然后在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();
});
这个程序只显示“请输入第一个数字”,当我输入一个像5这样的数字时,第二个输入也需要5,并显示答案10
它根本不会问第二个问题。请检查一下,并告诉我问题出在哪里。如果有更好的方法接受多个输入,请告诉我。
我是node.js的新手
发布于 2018-02-14 23:33:03
嵌套的代码/回调很难阅读和维护,这里有一种更优雅的方式来使用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()
发布于 2016-08-02 18:34:10
不需要另一个变量,只需像这样使用:
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();
});
});
发布于 2019-08-09 00:18:43
我会在一个异步函数中提出问题,并包装readline,类似于Jason上面是如何做的。虽然代码稍微少了一点:)
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);
}
https://stackoverflow.com/questions/36540996
复制相似问题