如何从node.js中的用户获取控制台输入? [英] How can I take console input from a user in node.js?

查看:1062
本文介绍了如何从node.js中的用户获取控制台输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试转移到cloud9作为全时IDE,因为它似乎是我的chromebook上的最佳选择。但是,我正在尝试制作一个需要用户输入文本的基本程序,但我教的代码 var x = prompt(y); 似乎没有在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.

如何获取用户输入并将其存储为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();
});

取自此处 http://nodejs.org/api/readline.html#readline_readline

更具体地说,填写此代码到app.js文件,然后运行以下命令

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

node app.js

并回答上述问题。

会发生什么? require语句公开'readline'模块的公共方法,其中一个是'createInterface'方法。此方法将输入和输出作为选项。

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.

从外观上看,可以指定不同的输入和输出源,但在这种情况下,您使用的是'全局节点进程变量的stdin'和'stdout'属性。这些指定输入和输出来自控制台。

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.

接下来,您调用您创建的readline对象的问题方法,并指定一个回调函数来显示用户输入回到用户。在readline上调用'close'以将控制权释放回调用者。

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.

这篇关于如何从node.js中的用户获取控制台输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆