如何在node.js中读取用户输入以进行简单计算
如何从node.js中的命令行读取用户输入以进行简单计算?我一直在阅读,但我不能将我的输入用于像如何在node.js中读取用户输入以进行简单计算,node.js,Node.js,如何从node.js中的命令行读取用户输入以进行简单计算?我一直在阅读,但我不能将我的输入用于像console.log(input)这样的简单事情。我知道这些是异步函数,但我想一定有一种方法可以在以后的计算中使用输入 你有一个例子吗?比如两个给定数字的和:输入a和b,输出a+b,像这样吗 var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, ou
console.log(input)
这样的简单事情。我知道这些是异步函数,但我想一定有一种方法可以在以后的计算中使用输入
你有一个例子吗?比如两个给定数字的和:输入a和b,输出a+b,像这样吗
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function processSum(number) {
// Insert code to do whatever with sum here.
console.log('The sum is', number);
}
rl.question('Enter a number: ', function (x) {
rl.question('Enter another number: ', function (y) {
var sum = parseFloat(x) + parseFloat(y);
processSum(sum)
rl.close();
});
});
您可以编写如下可重用模块:
// ask.js
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.pause();
function ask(question, cb = () => void 0) {
return new Promise(resolve => {
rl.question(question, (...args) => {
rl.pause();
resolve(...args);
cb(...args);
});
});
}
module.exports = ask;
并在任何地方使用多种方法:
进近#1(使用异步/等待
):
方法#2(带有承诺):
进近#3(带回叫
):
您不能在回调之外引用sum(我假设您正试图这么做)。在我更新的答案中,您将把处理sum的所有代码都放在函数processSum中。
const ask = require("./ask");
(async () => {
const a = await ask("Enter the first number: ");
const b = await ask("Enter the second number: ");
console.log("The sum is", a + b);
})();
const ask = require("./ask");
ask("Enter the first number: ")
.then(a => {
ask("Enter the second number: ")
.then(b => {
console.log("The sum is", a + b);
});
});
const ask = require("./ask");
ask("Enter the first number: ", a => {
ask("Enter the second number: ", b => {
console.log("The sum is ", a + b);
});
});