You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中使用readline模块存储控制台用户输入并在其他函数中调用执行操作的实现方法

How to Store User Input from readline and Use It in Other Functions (Node.js)

Great question! The confusion here boils down to asynchronous code execution—a key difference from synchronous languages like C++. readline.question() doesn't pause your program to wait for user input; it runs in the background, and your code keeps executing until the user types a response (triggering the callback function). Let's break down how to fix this and use your input values in the sum() function.

Solution 1: Call Your Function Directly in the Callback (Simplest Approach)

Since you only get both input values once the second question() callback runs, you can call sum() right there. Just remember to convert input strings to numbers first—all readline input comes as strings, and adding them directly would concatenate instead of calculate a sum:

const readline = require('readline').createInterface({ 
  input: process.stdin, 
  output: process.stdout, 
})

readline.question('Enter number 1: ', function (a) {
  readline.question('Enter number 2: ', function (b) {
    // Convert string inputs to numeric values
    const num1 = Number(a);
    const num2 = Number(b);
    
    // Call sum() with the valid numbers we've collected
    const total = sum(num1, num2);
    console.log(`The sum is: ${total}`);
    
    readline.close();
  })
})

function sum(num1, num2) {
  return num1 + num2;
}

Solution 2: Use Promises + Async/Await (Cleaner, Synchronous-Looking Code)

If nested callbacks feel messy (sometimes called "callback hell"), you can wrap readline.question() in a Promise, then use async/await to write code that flows like the synchronous C++ you're used to:

const readline = require('readline').createInterface({ 
  input: process.stdin, 
  output: process.stdout, 
})

// Wrap readline.question in a Promise to make it awaitable
function askUser(prompt) {
  return new Promise((resolve) => {
    readline.question(prompt, resolve);
  });
}

// Main async function to handle input and logic
async function calculateSum() {
  // Wait for user input (code pauses here until the user responds)
  const input1 = await askUser('Enter number 1: ');
  const input2 = await askUser('Enter number 2: ');
  
  // Convert inputs to numbers
  const num1 = Number(input1);
  const num2 = Number(input2);
  
  // Call sum and log the result
  const total = sum(num1, num2);
  console.log(`Sum of ${num1} and ${num2} is: ${total}`);
  
  readline.close();
}

function sum(num1, num2) {
  return num1 + num2;
}

// Run the main function to start the process
calculateSum();

This approach makes your code linear and easy to follow, just like synchronous code.

Critical Notes to Avoid Mistakes

  • Always convert input to numbers: Skip this step, and adding a and b will give you a string (e.g., inputting 1 and 2 results in "12" instead of 3).
  • Avoid relying on global variables: You could declare variables outside the callbacks and assign them inside, but you can't guarantee when those variables will be populated. Calling sum() before the callbacks run will result in undefined values.
  • Understand asynchronous order: Node.js runs non-blocking code first. Any code outside your callbacks or await statements will execute before the user inputs are received.

内容的提问来源于stack exchange,提问作者Infinity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:57:26