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

一世执手 提交于 2019-11-27 04:39:39

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26683734/how-can-i-take-console-input-from-a-user-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!