Javascript 如何从 node.js 中的用户获取控制台输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26683734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I take console input from a user in node.js?
提问by Lewiky
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.
我尝试将 cloud9 作为全职 IDE,因为它似乎是我的 chromebook 上的最佳选择。但是,我正在尝试制作一个需要用户输入文本的基本程序,但我所教的代码var x = prompt("y");似乎在 node.js 中不起作用。
How can I take user input and store it as a variable in node.js?
如何获取用户输入并将其作为变量存储在 node.js 中?
回答by UberTechnoMancer
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
取自这里http://nodejs.org/api/readline.html#readline_readline
More specifically, stuff this code into an app.js file, then run the following command
更具体地说,将此代码填充到 app.js 文件中,然后运行以下命令
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.
发生什么了?require 语句公开了“readline”模块的公共方法,其中之一是“createInterface”方法。此方法将输入和输出作为选项。
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.
从它的外观来看,可以指定不同的输入和输出源,但在这种情况下,您使用的是全局节点“process”变量的“stdin”和“stdout”属性。这些指定了控制台的输入和输出。
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.
接下来调用已创建的 readline 对象的 question 方法并指定回调函数以将用户输入显示回用户。在 readline 上调用“close”以将控制权释放回调用者。
回答by Zak
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.
您只能在浏览器中使用 JavaScript 的 BOM(浏览器对象模型)功能,而不能在 Node JS 中使用。

