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

Zem*_*rof 11 javascript keyboard input actionlistener node.js

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

var color = 'blue'
Run Code Online (Sandbox Code Playgroud)

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

Har*_*lin 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.");
Run Code Online (Sandbox Code Playgroud)


小智 8

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();
});
Run Code Online (Sandbox Code Playgroud)


Aru*_*ITH 5

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();
});
Run Code Online (Sandbox Code Playgroud)
  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 )

将输入作为 argv:

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


Ale*_*hov 3

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