2

How can I read user input from the command line in node.js for simple calculations? I'v been reading http://nodejs.org/api/readline.html#readline_readline and http://nodejs.org/api/process.html#process_process_stdin but I can't use my input for simple things like console.log(input). I know these are async functions, but I guess there must be a way of using the input for later calculations.

Do you have an example? Like a sum of two given numbers: input a and b and output a+b

2 Answers 2

4

Something like this?

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();
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

You can't refer to sum outside of the callbacks (I assume that's what you're trying to do). In my updated answer, you would put all the code to process sum in the function processSum.
1

You could write a reusable module like this:

// 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;

And use it with multiple approaches everywhere:

Approach #1 (with async/await):

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);
})();

Approach #2 (with Promise):

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);
      });
  });

Approach #3 (with callback):

const ask = require("./ask");

ask("Enter the first number: ", a => {
  ask("Enter the second number: ", b => {
    console.log("The sum is ", a + b);
  });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.