Question

I'm currently using spidermonkey to run my JavaScript code. I'm wondering if there's a function to get input from the console similar to how Python does this:

var = raw_input()  

Or in C++:

std::cin >> var;

I've looked around and all I've found so far is how to get input from the browser using the prompt() and confirm() functions.

OTHER TIPS

In plain JavaScript, simply use response = readline() after printing a prompt.

In Node.js, you'll need to use the readline module: const readline = require('readline')

As you mentioned, prompt works for browsers all the way back to IE:

var answer = prompt('question', 'defaultAnswer');

prompt in IE

For Node.js > v7.6, you can use console-read-write, which is a wrapper around the low-level readline module:

const io = require('console-read-write');

async function main() {
  // Simple readline scenario
  io.write('I will echo whatever you write!');
  io.write(await io.read());

  // Simple question scenario
  io.write(`hello ${await io.ask('Who are you?')}!`);

  // Since you are not blocking the IO, you can go wild with while loops!
  let saidHi = false;
  while (!saidHi) {
    io.write('Say hi or I will repeat...');
    saidHi = await io.read() === 'hi';
  }

  io.write('Thanks! Now you may leave.');
}

main();
// I will echo whatever you write!
// > ok
// ok
// Who are you? someone
// hello someone!
// Say hi or I will repeat...
// > no
// Say hi or I will repeat...
// > ok
// Say hi or I will repeat...
// > hi
// Thanks! Now you may leave.

Disclosure I'm author and maintainer of console-read-write

For SpiderMonkey, simple readline as suggested by @MooGoo and @Zaz.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top