node.js 如何从键盘接收文本输入并将其存储到变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19718669/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:09:17  来源:igfitidea点击:

How to take in text input from a keyboard and store it into a variable?

javascriptnode.jsinputkeyboardactionlistener

提问by Zemprof

I would just like something simple to read text from a keyboard and store it into a variable. So for:

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

var color = 'blue'

I would like the user to provide input for the color from the keyboard. Thank you!

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

回答by Harlin

I would suggest the readline-sync module as well if you don't require something asynchronous.

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

回答by Olutobi Adeyemi

Node has a built in API for this...

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

回答by ArunDhwaj IIITH

There are three solution for it on NodeJS platform

NodeJS平台上有三种解决方案

  1. For asynchronous use case need, use Node API: readline
  1. 对于异步用例需求,请使用Node API:readline

Like: ( https://nodejs.org/api/readline.html)

喜欢:(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. For synchronous use case need, use NPM Package: readline-syncLike: ( https://www.npmjs.com/package/readline-sync)

    var readlineSync = require('readline-sync');

    // Wait for user's response. var userName = readlineSync.question('May I have your name? '); console.log('Hi ' + userName + '!');

  2. For all general use case need, use **NPM Package: global package: process: ** Like: ( https://nodejs.org/api/process.html)

  1. 对于同步用例需要,使用NPM 包:readline-sync喜欢:(https://www.npmjs.com/package/readline-sync

    var readlineSync = require('readline-sync');

    // 等待用户的响应。var userName = readlineSync.question('可以告诉我你的名字吗?'); console.log('嗨' + 用户名 + '!');

  2. 对于所有一般用例需要,使用 **NPM Package: global package: process: ** Like: ( https://nodejs.org/api/process.html)

For taking input as argv:

将输入作为 argv:

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

回答by Sagar Gavhane

We can also use NodeJS core standard input functionality for the same. ctrl+Dfor end standard input data reading.

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

回答by sgmonda

You can use stdiofor this. It is as simple as follows:

您可以为此使用stdio。它很简单,如下所示:

import { ask } from 'stdio';
const color = await ask('What is your keyboard color?');

This module includes retries if you decide to accept only some predefined answers:

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

import { ask } from 'stdio';
const color = await ask('What is your keyboard color?', { options: ['red', 'blue', 'orange'], maxRetries: 3 });

Take a look at stdio, it includes other features that may be useful for you (like command-line arguments parsing, standard input reading at once or by lines...).

看看stdio,它包括其他可能对您有用的功能(例如命令行参数解析,一次或按行读取标准输入......)。

回答by Alex Netkachov

You can use the module 'readline' for this: http://nodejs.org/api/readline.html- the first example in the manual demonstrates how to do what you asked for.

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

回答by Vinte Segundos

If I understood your need, that should do it:

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

html:

html:

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

javascript:

javascript:

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

if you don't need to do something everytime the input changes, you can just get the input whenever you want to do something with 'color':

如果您不需要在每次输入更改时都执行某些操作,则可以在想要使用“颜色”执行某些操作时获取输入:

html:

html:

<input id="userInput">

javascript:

javascript:

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