Ask coding questions

← Back to all posts
2
Reading Console Input using Node.js
vedprad1 (477)

Reading Console Input using Node.js

Is it possible to take in Console Input using Node.js? My way is not working.
The Repl

Commentshotnewtop
3
Pythonier (300)

It is possible, I don't code Node.js but I found this from https://flaviocopes.com/node-input-from-cli/

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

readline.question(`What's your name?`, (name) => {
  console.log(`Hi ${name}!`)
  readline.close()
})

Hope that helps!

2
vedprad1 (477)

@Pythonier : That's exactly what I have! However, it just displays the question and skips the input and the action after the input.

3
Pythonier (300)

@vedprad1 Weird, try requiring readline-sync instead. ex:

const readline = require("readline-sync");
var name = readline.question("What is your name? ");
3
Pythonier (300)

@vedprad1 Is this what you are looking for:

var rl = require('readline-sync');
rl.question("What do you think of node.js? ")
console.log("Thank you for your valuable feedback.");
2
vedprad1 (477)

@Pythonier : This seems to work! Thanks!

3
Pythonier (300)

@vedprad1

If that was helpful can you please mark my comment as the answer.