20

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!

Flip
  • 6,233
  • 7
  • 46
  • 75
Zemprof
  • 245
  • 1
  • 2
  • 10
  • You can make use of the sample code available at this [similar question](http://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin). The questioner's code is probably enough. – eddie.sholl Nov 01 '13 at 00:01

8 Answers8

20

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

# 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.");
Harlin
  • 1,059
  • 14
  • 18
10

Node has a built in API for this...

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();
});
Olutobi Adeyemi
  • 195
  • 2
  • 6
6

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 + '!');
  1. 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}`);
});
Andres Gardiol
  • 1,312
  • 15
  • 22
ArunDhwaj IIITH
  • 3,833
  • 1
  • 24
  • 14
3

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.

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85
3

You can use stdio for this. It is as simple as follows:

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...).

sgmonda
  • 2,615
  • 1
  • 19
  • 29
3

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

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);
}
Sagar
  • 4,473
  • 3
  • 32
  • 37
0

You can use this templete

process.stdin.resume();
// A Readable Stream that points to a standard input stream (stdin)
process.stdin.setEncoding("utf-8"); // so that the input doesn't transform

let inputString1 = "";
let inputString = "";
let currentLine = 0;

process.stdin.on("data", function (userInput) {
  inputString1 = inputString1 + userInput; // taking the input string
});

process.stdin.on("end", function (x) {
  inputString1.trim();
  inputString1 = inputString1.split("\n"); // end line
  for (let i = 0; i < inputString1.length; i++) {
    inputString += inputString1[i].trim() + " ";
  }
  inputString.trim();
  inputString = inputString.split(" ");
  main();
});

function readline() {
  let result = inputString[currentLine++];
  return parseInt(result); // change when you want to use strings, according to the problem
}

function main() {
  let n = readline();
  let arr = [];
  for (let i = 0; i < n; i++) {
    arr[i] = readline();
  }
}
PR7
  • 1,524
  • 1
  • 13
  • 24
-3

If I understood your need, that should do it:

html:

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

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:

<input id="userInput">

javascript:

color=document.getElementById("userInput").value;
  • 1
    I think the OP was asking for something from the command line -- I have to assume that since he mentioned "take text input from a keyboard...". – Harlin May 27 '16 at 02:10