如何从键盘输入文本输入并将其存储到变量中?

问题描述 投票:9回答:7

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

var color = 'blue'

我希望用户从键盘提供颜色输入。谢谢!

javascript node.js input keyboard actionlistener
7个回答
12
投票

如果您不需要异步,我建议使用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.");

6
投票

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();
});

3
投票

在NodeJS平台上有三种解决方案

  1. 对于异步使用案例需求,请使用Node API:readline

喜欢:(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();
});
  1. 对于同步用例需要,使用NPM包:readline-sync喜欢:(https://www.npmjs.com/package/readline-sync) var readlineSync = require('readline-sync'); //等待用户的回复var userName = readlineSync.question('我可以叫你的名字吗?'); console.log('Hi'+ userName +'!');
  2. 对于所有一般用例需要,使用** NPM包:全局包:进程:**喜欢:(https://nodejs.org/api/process.html

以argv作为输入:

// print process.argv
process.argv.forEach((val, index) => 
{
  console.log(`${index}: ${val}`);
});

2
投票

你可以使用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,它包含可能对你有用的其他功能(比如命令行参数解析,标准输入读取一次或按行...)。我是stdio的创建者,我刚刚发布了0.2.0版本。 :-)

NPM


1
投票

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


1
投票

我们也可以使用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);
}

-1
投票

如果我了解你的需要,那应该这样做:

HTML:

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

JavaScript的:

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

如果你不想在每次输入改变时都做某事,只要你想用'color'做什么就可以得到输入:

HTML:

<input id="userInput">

JavaScript的:

color=document.getElementById("userInput").value;
© www.soinside.com 2019 - 2024. All rights reserved.