简体   繁体   中英

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?

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.

Take a look at Reading value from console, interactively .

You can only use JavaScript's BOM (Browser Object Model) functionality within a browser, not with in Node JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM