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
stdinto receive user input or piped data. - Coding challenge platforms often expect solutions to read from
stdin. - Scripts and automation use
stdinto accept values from other commands.
A common beginner pattern is:
- Listen for incoming data.
- Collect it into a string.
- Wait until input ends.
- 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.
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
inputstores everything read fromstdinsetEncoding('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..();
process..(, {
input += chunk;
});
process..(, {
lines = input.().();
name = lines[];
age = (lines[]);
.();
});
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
-
let input = ''- Creates an empty string to store incoming text.
-
process.stdin.setEncoding('utf8')- Tells Node to read text instead of raw binary data.
-
process.stdin.on('data', chunk => { ... })- Registers a callback for each piece of input received.
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.
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) {
age = (value);
(.(age)) {
.();
process.();
}
age;
}
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', {
input += chunk;
});
Comparisons
| Approach | Best for | Notes |
|---|---|---|
process.stdin.on('data') + 'end' | Reading all input in Node.js | Most common pattern for scripts and coding challenges |
readline module | Interactive line-by-line input | Better when asking the user questions one line at a time |
Command-line arguments (process.argv) | Short values passed when starting the program | Good for flags and fixed parameters, not streamed input |
stdin vs command-line arguments
| Feature | stdin | process.argv |
|---|
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.stdinis for Node.js, not the browser.- Input is usually read as strings.
- Data may arrive in multiple chunks.
- Use
input += chunk, notinput = 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
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.
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
- Read all input from
stdinusing Node.js. - Split the input into lines.
- Ignore empty lines.
- Print each non-empty name with a number starting from 1.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.