What if you could handle huge files without your app freezing or crashing?
Streams vs loading entire file in memory in Node.js - When to Use Which
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you want to read a huge video file to process it. You try to load the entire file into memory at once before doing anything.
Loading the whole file at once can crash your program if the file is too big. It also wastes memory and makes your app slow and unresponsive.
Streams let you read the file bit by bit, like a flowing river, so you never hold the entire file in memory. This keeps your app fast and stable.
const fs = require('fs'); const data = fs.readFileSync('bigfile.mp4'); process(data);
const fs = require('fs'); const stream = fs.createReadStream('bigfile.mp4'); stream.on('data', chunk => process(chunk));
Streams enable efficient handling of large files or data without freezing or crashing your app.
Streaming a movie online without downloading the whole file first, so you can start watching immediately.
Loading entire files uses lots of memory and can crash apps.
Streams read data in small parts, saving memory and improving speed.
Using streams makes apps handle big data smoothly and efficiently.
Practice
Solution
Step 1: Understand how streams work
Streams read data piece by piece, not all at once, which uses less memory.Step 2: Compare with loading entire file
Loading entire file reads all data into memory, which can be heavy for big files.Final Answer:
Streams process data in small chunks, saving memory. -> Option DQuick Check:
Streams = small chunks, less memory [OK]
- Thinking streams load files faster always
- Believing streams compress data automatically
- Assuming streams require less code always
data.txt in Node.js?Solution
Step 1: Recall Node.js stream syntax
The correct method to create a readable stream isfs.createReadStream(filename).Step 2: Check each option
Only const stream = fs.createReadStream('data.txt'); uses the correct method name and syntax.Final Answer:
const stream = fs.createReadStream('data.txt'); -> Option AQuick Check:
Use createReadStream() to read files as streams [OK]
- Using fs.readFile() which reads whole file, not stream
- Using non-existent methods like openStream or streamFile
- Missing quotes around filename
const fs = require('fs');
let data = '';
const stream = fs.createReadStream('file.txt');
stream.on('data', chunk => { data += chunk; });
stream.on('end', () => { console.log(data.length); });What will this code output if
file.txt is 5000 bytes?Solution
Step 1: Understand stream data event
The 'data' event adds chunks of the file to thedatastring as they arrive.Step 2: Check what happens on 'end'
When the stream ends,data.lengthis logged, which equals the total bytes read (5000).Final Answer:
It will print 5000 -> Option BQuick Check:
Stream chunks combined length = file size [OK]
- Assuming data is empty before 'end' event
- Expecting undefined because of async nature
- Thinking stream throws error without error handler
const fs = require('fs');
const stream = fs.createReadStream('bigfile.txt');
stream.on('data', chunk => { console.log(chunk.toString()); });What is the likely reason no output appears?
Solution
Step 1: Check if file exists
If the file path is wrong or file missing, stream emits error and no data event triggers.Step 2: Understand stream default behavior
Streams start flowing automatically when 'data' event is attached; no need to call resume().Final Answer:
The file path is incorrect or file does not exist. -> Option CQuick Check:
No output usually means file missing or wrong path [OK]
- Thinking 'end' event triggers reading
- Believing streams pause by default without resume()
- Removing 'data' event to fix reading
Solution
Step 1: Identify memory-efficient reading
Loading entire file or synchronous reading uses lots of memory and blocks event loop.Step 2: Combine streams with line parsing
Usingfs.createReadStream()withreadlinemodule reads file chunk by chunk and processes lines efficiently.Final Answer:
Use fs.createReadStream() with a line-by-line parser like readline module. -> Option AQuick Check:
Streams + readline = memory-efficient line processing [OK]
- Loading entire file for big logs causes memory issues
- Using synchronous methods blocks Node.js event loop
- Reading fixed buffers manually is complex and error-prone
