Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在node.js中读取用户输入以进行简单计算_Node.js - Fatal编程技术网

如何在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

如何从node.js中的命令行读取用户输入以进行简单计算?我一直在阅读,但我不能将我的输入用于像
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);
  });
});