Nodejs:如何从键盘接受文本input,并将其存储到JavaScript中的variables?

我只想简单地从键盘读取文本并将其存储到variables中。 因此对于:

var color = 'blue' 

我希望用户提供来自键盘的颜色的input。 谢谢!

您可以使用模块“readline”来获取: http : //nodejs.org/api/readline.html – 手册中的第一个例子演示了如何执行所要求的操作。

如果你不需要asynchronous的东西,我会build议readline-sync模块。

 # npm install readline-sync var readline = require('readline-sync'); var name = readline.question("What is your name?"); console.log("Hi " + name + ", nice to meet you."); 

节点有一个内置的API …

 const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Please enter a color? ', (value) => { let color = value console.log(`You entered ${color}`); rl.close(); }); 

你可以使用stdio来做到这一点。 它如下简单:

 var stdio = require('stdio'); stdio.question('What is your keyboard color?', function (err, color) { // Do whatever you want with "color" }); 

如果您决定只接受一些预定义的答案,则该模块包含重试:

 var stdio = require('stdio'); stdio.question('What is your keyboard color?', ['red', 'blue', 'orange'], function (err, color) { // Do whatever you want with "color" }); 

看看stdio ,它包含了其他可能对你有用的function(比如命令行参数parsing,标准input一次读取或按行…)。 我是stdio创造者,我刚刚发布了0.2.0版本。 🙂

NPM

如果我明白你的需要,那就应该这样做:

HTML:

 <input id="userInput" onChange="setValue()" onBlur="setValue()"> 

JavaScript的:

 function setValue(){ color=document.getElementById("userInput").value; //do something with color } 

如果每次input更改时不需要执行某些操作,则只要您想用“颜色”进行操作,就可以获得input:

HTML:

 <input id="userInput"> 

JavaScript的:

 color=document.getElementById("userInput").value;