75

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
camel_space
  • 1,057
  • 1
  • 7
  • 10

5 Answers5

58

Good old readline();.

See MDN (archive).

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
MooGoo
  • 46,796
  • 4
  • 39
  • 32
19

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')

Zaz
  • 46,476
  • 14
  • 84
  • 101
  • 12
    ` var x = readline(); ^ TypeError: readline is not a function ` after adding require at the top of the file – fIwJlxSzApHEZIl Nov 13 '17 at 23:20
  • 1
    Also had the same problem. – Devin Haslam Jan 04 '18 at 23:15
  • 1
    That's weirder than ever. – Machado Sep 26 '18 at 03:27
  • 2
    readline does not work the same in node. you need something like this: const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }) readline.question("what's your name? ", name => { console.log(`Hello ${name}`); readline.close(); }); – kDar Jan 06 '20 at 15:36
  • 1
    @kDar I prefer to do name => { readline.close(); console.log(name); } In my case, your version doesn't show input while typing. Anyway, thanks for your comment – Marco M. von Hagen Jul 18 '20 at 15:43
16

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.

Keyvan
  • 813
  • 9
  • 19
0

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing

[                                                                                                                                                                                          
  '/usr/bin/node',                                                                                                                                                                         
  '/home/user/path/filename.js',                                                                                                                                            
  'your_input'                                                                                                                                                                                   
]

You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


Example:

var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);

If you are building a command-line program then the npm package yargs would be really helpful.

ArcherL
  • 39
  • 5
0

Node.js has built-in readline module.

one example:

const readline = require('readline')
const rl = readline.createInterface({
   input: process.stdin,
   output: process.stdout,
});
rl.question(`Are you sure? (yes/no): `, async answer => {
   if (answer.toLocaleLowerCase() === 'yes') {
     console.log('processing...');
   }
   else {
     console.log('aborting...');
   }
});

M. Emre Yalçın
  • 608
  • 1
  • 7
  • 10