【发布时间】:2013-11-12 04:13:40
【问题描述】:
我想要一些简单的东西来从键盘读取文本并将其存储到变量中。所以对于:
var color = 'blue'
我希望用户从键盘输入颜色。谢谢!
【问题讨论】:
-
您可以使用similar question 提供的示例代码。提问者的代码大概就够了。
标签: javascript node.js input keyboard actionlistener
我想要一些简单的东西来从键盘读取文本并将其存储到变量中。所以对于:
var color = 'blue'
我希望用户从键盘输入颜色。谢谢!
【问题讨论】:
标签: javascript node.js input keyboard actionlistener
如果您不需要异步的东西,我也建议使用 readline-sync 模块。
# npm install readline-sync
const readline = require('readline-sync');
let name = readline.question("What is your name?");
console.log("Hi " + name + ", nice to meet you.");
【讨论】:
Node 有一个内置的 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();
});
【讨论】:
在NodeJS平台上有三种解决方案
点赞:(https://nodejs.org/api/readline.html)
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
});
对于同步用例需要,使用 NPM 包: readline-sync 喜欢:(https://www.npmjs.com/package/readline-sync)
var readlineSync = require('readline-sync');
// 等待用户响应。 var userName = readlineSync.question('我可以知道你的名字吗?'); console.log('Hi' + 用户名 + '!');
对于所有一般用例需要,使用 **NPM Package: global package: process: ** Like: (https://nodejs.org/api/process.html)
将输入作为 argv:
// print process.argv
process.argv.forEach((val, index) =>
{
console.log(`${index}: ${val}`);
});
【讨论】:
您可以为此使用模块“readline”:http://nodejs.org/api/readline.html - 手册中的第一个示例演示了如何按照您的要求进行操作。
【讨论】:
我们也可以使用 NodeJS 的核心标准输入功能。
ctrl+D 用于结束标准输入数据读取。
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var input_data = "";
process.stdin.on("data", function(input) {
input_data += input; // Reading input from STDIN
if (input === "exit\n") {
process.exit();
}
});
process.stdin.on("end", function() {
main(input_data);
});
function main(input) {
process.stdout.write(input);
}
【讨论】:
您可以为此使用stdio。就这么简单:
import { ask } from 'stdio';
const color = await ask('What is your keyboard color?');
如果您决定只接受一些预定义的答案,则此模块包括重试:
import { ask } from 'stdio';
const color = await ask('What is your keyboard color?', { options: ['red', 'blue', 'orange'], maxRetries: 3 });
看看stdio,它包含其他可能对您有用的功能(如命令行参数解析、标准输入一次或逐行读取......)。
【讨论】:
如果我了解您的需求,那应该可以:
html:
<input id="userInput" onChange="setValue()" onBlur="setValue()">
javascript:
function setValue(){
color=document.getElementById("userInput").value;
//do something with color
}
如果您不需要在每次输入更改时都执行某项操作,则只要您想使用“颜色”执行某项操作即可获取输入:
html:
<input id="userInput">
javascript:
color=document.getElementById("userInput").value;
【讨论】: