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

前端 未结 7 2110
清酒与你
清酒与你 2020-12-30 05:43

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

7条回答
  •  没有蜡笔的小新
    2020-12-30 05:56

    There are three solution for it on NodeJS platform

    1. For asynchronous use case need, use Node API: readline

    Like: ( 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-sync Like: ( 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 )

    For taking input as argv:

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

提交回复
热议问题