Question

How to Read from stdin in JavaScript

pythonstdin

Question

How do I read from standard input (stdin) in JavaScript?

For example, how can I accept input entered by the user in a terminal, store it in variables, and then process it in a Node.js program?

Short Answer

By the end of this page, you will understand what stdin is, how Node.js reads terminal input, and the common ways to collect and process user input in JavaScript. You will also see practical examples, common mistakes, and a small project that uses stdin in a realistic way.

Concept

Standard input, usually called stdin, is the default input stream for a program. When you run a program in a terminal and type something, that text can be sent into the program through stdin.

In JavaScript, stdin is commonly used in Node.js, not in browser JavaScript. Node exposes it through:

process.stdin

This object is a readable stream. That means input does not always arrive all at once. Instead, data may come in chunks over time.

Why this matters:

  • Command-line tools use stdin to receive user input or piped data.
  • Coding challenge platforms often expect solutions to read from stdin.
  • Scripts and automation use stdin to accept values from other commands.

A common beginner pattern is:

  1. Listen for incoming data.
  2. Collect it into a string.
  3. Wait until input ends.
  4. Split or parse the text.

For example, if the user enters:

Alice
25

Your program can read that as raw text, then split it by lines and process each value.

The key idea is that stdin gives your program a stream of input, and your job is usually to collect that input and convert it into the format you need.

Mental Model

Think of stdin like a mailbox slot for your program.

  • The terminal user drops messages into the slot.
  • Your program checks the slot through process.stdin.
  • The messages may arrive piece by piece.
  • Once the mail stops coming, your program can open everything and sort it.

Another way to think about it: stdin is like a microphone connected to your program. The program listens, gathers what it hears, and then decides what to do with it.

Take Quiz

Syntax and Examples

The most common Node.js pattern for reading all input from stdin is:

let input = '';

process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  console.log('You entered:');
  console.log(input);
});

What this does

  • input stores everything read from stdin
  • setEncoding('utf8') tells Node to treat input as text
  • 'data' runs whenever a new chunk arrives
  • 'end' runs when there is no more input

Example: read lines into variables

let input = '';

process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  const lines = input.trim().split('\n');

  const name = lines[0];
  const age = Number(lines[1]);

  console.log(`Hello, ${name}. You are ${age} years old.`);
});

If the input is:

Alice
25

The output will be:

Hello, Alice. You are 25 years old.

Example: read space-separated numbers

let input = '';

process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  const numbers = input.trim().split(/\s+/).map(Number);
  console.log(numbers);
});

Input:

10 20 30 40

Output:

[ 10, 20, 30, 40 ]

This is especially useful in coding problems where values are separated by spaces or newlines.

Step by Step Execution

Consider this program:

let input = '';

process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  const words = input.trim().split(/\s+/);
  console.log(words);
});

Suppose the user provides this input:

red blue green

Step by step

  1. let input = ''

    • Creates an empty string to store incoming text.
  2. process.stdin.setEncoding('utf8')

    • Tells Node to read text instead of raw binary data.
  3. process.stdin.on('data', chunk => { ... })

    • Registers a callback for each piece of input received.
    • If the terminal sends "red blue green\n", that chunk gets appended to input.
  4. After input finishes, process.stdin.on('end', ...) runs.

    • Now input contains the full text.
  5. input.trim()

    • Removes extra whitespace at the beginning or end, including the final newline.
  6. .split(/\s+/)

    • Splits the string on one or more whitespace characters.
    • Result: ['red', 'blue', 'green']
  7. console.log(words)

    • Prints the array.

Important detail

'data' may run more than once. That is why we append:

input += chunk;

If you overwrite instead of append, you could lose part of the input.

Real World Use Cases

Reading from stdin is useful in many real programs:

Command-line tools

A CLI program may ask for input or accept piped data:

echo "hello" | node app.js

Your script reads hello from stdin.

Coding challenge platforms

Sites that test algorithms often provide input through stdin. Your program reads it, parses it, and prints the answer.

Data processing scripts

You can pass text files or command output into a Node script:

cat users.txt | node process-users.js

Interactive terminal programs

Some scripts let users type values directly, such as names, menu choices, or commands.

DevOps and automation

Scripts can receive configuration or input from shell commands without hardcoding values into the program.

Take Quiz

Real Codebase Usage

In real codebases, developers usually do more than just read raw text. They combine stdin with parsing, validation, and program flow patterns.

Common patterns

1. Parse once, then process

Developers often collect all input first, then parse it in one place.

let input = '';
process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  const lines = input.trim().split('\n');
  run(lines);
});

function run(lines) {
  console.log(lines);
}

This keeps input handling separate from business logic.

2. Validation

Real programs check whether input is missing or invalid.

function parseAge(value) {
  const age = Number(value);

  if (Number.isNaN(age)) {
    console.error('Invalid age');
    process.exit(1);
  }

  return age;
}

3. Guard clauses

Guard clauses stop the program early when required input is not present.

if (!input.trim()) {
  console.error('No input provided');
  process.exit(1);
}

4. Transforming input with map

A common pattern is to split text and convert it.

const nums = input.trim().split(/\s+/).map(Number);

5. Error output vs normal output

In CLI tools, developers often print errors with console.error() and normal results with console.log().

This makes scripts easier to combine with other tools.

Common Mistakes

Here are common beginner mistakes when reading from stdin in Node.js.

1. Assuming browser JavaScript has process.stdin

process.stdin is a Node.js feature, not a browser feature.

Broken idea:

process.stdin.on('data', chunk => {
  console.log(chunk);
});

If you run this in a browser environment, it will not work.

2. Forgetting that input may come in chunks

Broken code:

let input = '';

process.stdin.on('data', chunk => {
  input = chunk;
});

Problem:

  • This replaces previous input instead of keeping it.

Correct version:

let input = '';

process.stdin.on('data', chunk => {
  input += chunk;
});

3. Not trimming the final newline

Broken code:

const name = input.split('\n')[0];

This may still work, but extra whitespace can cause problems later.

Safer version:

const name = input.trim().split('\n')[0];

4. Forgetting to convert strings to numbers

Input from stdin is text.

Broken code:

const parts = input.trim().split(' ');
console.log(parts[0] + parts[1]);

If input is 10 20, output becomes:

1020

Correct version:

const parts = input.trim().split(' ').map(Number);
console.log(parts[0] + parts[1]);

5. Using the input before 'end'

Broken code:

let input = '';

process.stdin.on('data', chunk => {
  input += chunk;
});

console.log(input);

Problem:

  • console.log(input) runs before input is fully received.

Correct version:

process.stdin.on('end', () => {
  console.log(input);
});

6. Splitting only on a single space

Broken code:

const values = input.trim().split(' ');

If the input has multiple spaces or newlines, parsing may fail.

Better version:

const values = input.trim().split(/\s+/);

Comparisons

ApproachBest forNotes
process.stdin.on('data') + 'end'Reading all input in Node.jsMost common pattern for scripts and coding challenges
readline moduleInteractive line-by-line inputBetter when asking the user questions one line at a time
Command-line arguments (process.argv)Short values passed when starting the programGood for flags and fixed parameters, not streamed input

stdin vs command-line arguments

Featurestdinprocess.argv
Input sourceStreamed inputValues after the command
Good for large textYesNo
Good for piped dataYesNo
Good for simple optionsSometimesYes

process.stdin vs readline

process.stdin gives low-level stream access.

let input = '';
process.stdin.on('data', chunk => {
  input += chunk;
});

readline is more convenient for interactive terminal use.

const readline = require('readline');

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

rl.question('What is your name? ', answer => {
  console.log(`Hello, ${answer}`);
  rl.close();
});

Use process.stdin when you want raw streamed input. Use readline when you want a question-and-answer style interface.

Take Quiz

Cheat Sheet

// Basic stdin pattern in Node.js
let input = '';

process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  input += chunk;
});

process.stdin.on('end', () => {
  console.log(input);
});

Quick rules

  • process.stdin is for Node.js, not the browser.
  • Input is usually read as strings.
  • Data may arrive in multiple chunks.
  • Use input += chunk, not input = chunk.
  • Wait for 'end' before final processing.
  • Use trim() to remove trailing newlines.
  • Use split(/\s+/) for flexible whitespace splitting.
  • Use map(Number) to convert numeric input.

Common parsing patterns

const lines = input.trim().split('\n');
const words = input.trim().split(/\s+/);
const nums = input.trim().split(/\s+/).map(Number);

Interactive input

Use readline if you want prompts like:

rl.question('Enter your name: ', answer => {
  console.log(answer);
});

Edge cases

  • Empty input: check if (!input.trim())
  • Invalid numbers: use Number.isNaN(value)
  • Multiple spaces/newlines: prefer /\s+/ over ' '

FAQ

How do I read input from stdin in Node.js?

Use process.stdin and listen for 'data' and 'end' events. Collect the chunks into a string, then process the full input when it ends.

What is stdin in JavaScript?

In JavaScript, stdin usually refers to standard input in Node.js. It is the input stream your program can read from when running in a terminal.

Why do I need process.stdin.on('end')?

Because input may arrive in multiple chunks. The 'end' event tells you all input has been received, so it is safe to parse.

How do I read numbers from stdin?

Read the input as text, split it, and convert values with Number.

const nums = input.trim().split(/\s+/).map(Number);

How do I read line-by-line input in Node.js?

You can split the full input using split('\n'), or use the readline module for interactive line-by-line reading.

Is process.stdin available in the browser?

No. It is a Node.js API, not a browser API.

Should I use stdin or process.argv?

Use stdin for streamed or piped input. Use process.argv for command-line arguments like filenames, flags, or short options.

Take Quiz

Mini Project

Description

Build a small Node.js program that reads names from stdin and prints a numbered list. This demonstrates collecting terminal input, splitting it into lines, removing empty values, and processing the result into a useful output format.

Goal

Create a script that reads multiple names from standard input and prints each name with its position number.

Requirements

  1. Read all input from stdin using Node.js.
  2. Split the input into lines.
  3. Ignore empty lines.
  4. Print each non-empty name with a number starting from 1.
Take Quiz

Keep learning

Related questions

View more