【问题标题】:Get user input through Node.js console通过 Node.js 控制台获取用户输入
【发布时间】:2020-04-23 18:55:34
【问题描述】:

我刚开始使用 Node.js,我不知道如何获取用户输入。我正在寻找 Python 函数 input() 或 C 函数 gets 的 JavaScript 对应项。谢谢。

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您可以使用 3 个选项。我将向您介绍这些示例:

(选项 1)提示同步: 在我看来,这是更简单的一种。它是 npm 上的一个模块,您可以参考文档以获取更多示例 prompt-sync

npm install prompt-sync
const prompt = require("prompt-sync")({ sigint: true });
const age = prompt("How old are you? ");
console.log(`You are ${age} years old.`);

(选项 2)prompt:这是 npm 上可用的另一个模块:

npm install prompt
const prompt = require('prompt');

prompt.start();

prompt.get(['username', 'email'], function (err, result) {
    if (err) { return onErr(err); }
    console.log('Command-line input received:');
    console.log('  Username: ' + result.username);
    console.log('  Email: ' + result.email);
});

function onErr(err) {
    console.log(err);
    return 1;
}

(选项3)readline:它是Node.js中的内置模块。你只需要运行下面的代码:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("What is your name ? ", function(name) {
    rl.question("Where do you live ? ", function(country) {
        console.log(`${name}, is a citizen of ${country}`);
        rl.close();
    });
});

rl.on("close", function() {
    console.log("\nBYE BYE !!!");
    process.exit(0);
});

享受吧!

【讨论】:

    【解决方案2】:

    我认为这是一个更简单的选择

    npm install prompt-sync
    
    const prompt = require("prompt-sync")({ sigint: true });
    //With readline
    const name = prompt("What is your name?");
    console.log(`Hey there ${name}`);`enter code here`
    

    【讨论】:

    • SIgint 表示:“sigint:默认为false。在输入过程中可以按^C 以中止文本输入。如果sigint 为false,则提示返回null。如果sigint 为true,则^C将以传统方式处理:作为 SIGINT 信号导致进程以代码 130 退出。”,如果有人问
    • 是的,但你如何等待或处理承诺?
    【解决方案3】:

    这也可以通过 Promise 原生实现。它也比使用外部 NPM 模块更安全。不再需要使用回调语法。更新来自@Willian 的答案。这将适用于异步等待语法和 es6/7。

    
    const readline = require('readline');
    
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
    
    
    //usage inside aync function do not need closure demo only*
    (async () => {
      try{
        const name = await prompt('Whats your Name: ')
        //can use name for next question if needed
        const lastName = await prompt(`Hello ${name} Whats your Last name?:` )
        //can prompt multiple times.
        console.log(name,lastName);
        rl.close()
      }catch(e){
        console.errror("unable to prompt",e)
    }
    })()
       
    //when done reading prompt exit program 
    rl.on('close', () => process.exit(0))
    

    【讨论】:

      【解决方案4】:

      这也很好用:

      const fs = require('fs');
      
      process.stdin.resume();
      process.stdin.setEncoding('utf-8');
      
      let inputString = '';
      let currentLine = 0;
      
      process.stdin.on('data', inputStdin => {
          inputString += inputStdin;
      });
      
      process.stdin.on('end', _ => {
          inputString = inputString.replace(/\s*$/, '')
              .split('\n')
              .map(str => str.replace(/\s*$/, ''));
      
          main();
      });
      
      function readLine() {
          return inputString[currentLine++];
      }
      
      function main() {
          const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
      
          const n = parseInt(readLine(), 10); // Read and integer like this
      
          // Read an array like this
          const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));
      
          let result; // result of some calculation as an example
      
          ws.write(result + "\n");
      
          ws.end();
      }
      

      这里我的 process.env.OUTPUT_PATH 设置好了,如果你没有,你可以使用别的东西。

      【讨论】:

        【解决方案5】:

        我们可以使用内置的 readline 模块,它是标准 I/O 的包装器,适用于从命令行(终端)获取用户输入。

        这是一个简单的例子。在新文件中尝试以下操作:

        const readline = require("readline");
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
        
        rl.question("What is your name ? ", function(name) {
            rl.question("Where do you live ? ", function(country) {
                console.log(`${name}, is a citizen of ${country}`);
                rl.close();
            });
        });
        
        rl.on("close", function() {
            console.log("\nBYE BYE !!!");
            process.exit(0);
        });
        

        更多:How do I prompt users for input from a command-line script?

        【讨论】:

        【解决方案6】:

        提示包在“windows”环境下无法正常工作。

        而不是'inquirer'包更好

        【讨论】:

          【解决方案7】:

          使用这个: let inpt = Object.values(process.argv).slice(2).join(' ').toString();

          在运行文件时,您可以提供输入:
          例如:节点 .js

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 1970-01-01
          • 2014-12-28
          • 1970-01-01
          • 2013-04-24
          • 1970-01-01
          • 1970-01-01
          • 2015-04-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多