Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take console input from a user in node.js?

I tried moving to cloud9 as a full time IDE as it seems to be the best option on my chromebook. However, I'm trying to make a basic program that requires text input from the user but the code i was taught var x = prompt("y"); doesnt seem to work in node.js.

How can I take user input and store it as a variable in node.js?

like image 540
Lewiky Avatar asked Oct 31 '14 21:10

Lewiky


People also ask

How do I ask for console input in JavaScript?

In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned.

Can we take input from console in JavaScript?

However, what is not understandable is using JavaScript which runs only the browser, to get input from a systems command line. Doing this is possible using NodeJS. It will require us to use the readline() package. With this package, we can then accept user input and even output it to the console.

Can you console log in node JS?

log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.


1 Answers

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("What do you think of node.js? ", function(answer) {
  // TODO: Log the answer in a database
  console.log("Thank you for your valuable feedback:", answer);

  rl.close();
});

as taken from here http://nodejs.org/api/readline.html#readline_readline

More specifically, stuff this code into an app.js file, then run the following command

node app.js

And answer the question above.

What happens? the require statement exposes the public methods of the 'readline' module, one of which is 'createInterface' method. This method takes input and output as options.

From the looks of it, different sources of input and output can be specified, but in this case, you are using the 'stdin' and 'stdout' properties of the global node 'process' variable. These specify input and out to and from the console.

Next you call the question method of the readline object you've created and specify a callback function to display the user input back to user. 'close' is called on readline to release control back to the caller.

like image 137
UberTechnoMancer Avatar answered Oct 20 '22 08:10

UberTechnoMancer