我正在创建一个程序,从命令行输入两个数字,然后在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的初级用户
解决方法
不需要另一个变量,只需使用如下:
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(); }); });