Streams let you handle data bit by bit instead of all at once. This helps your program use less memory and work faster with big files.
Streams vs loading entire file in memory in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
const fs = require('fs'); // Using stream to read file const stream = fs.createReadStream('file.txt'); stream.on('data', chunk => { console.log('Received chunk:', chunk.toString()); }); // Reading entire file at once fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log('File content:', data.toString()); });
Streams use events like 'data' to handle chunks of data as they come.
Reading entire file loads all data into memory before you can use it.
const fs = require('fs'); // Stream example const readStream = fs.createReadStream('bigfile.txt'); readStream.on('data', chunk => { console.log('Chunk size:', chunk.length); });
const fs = require('fs'); // Read whole file fs.readFile('smallfile.txt', (err, data) => { if (err) throw err; console.log('File length:', data.length); });
This program shows both ways: streaming the file in parts and reading it all at once. You see chunks printed as they arrive, then the full content after reading all at once.
const fs = require('fs'); // Stream reading example console.log('Start streaming file...'); const stream = fs.createReadStream('example.txt'); stream.on('data', chunk => { console.log('Stream chunk:', chunk.toString()); }); stream.on('end', () => { console.log('Finished streaming file.'); }); // Read entire file example fs.readFile('example.txt', (err, data) => { if (err) throw err; console.log('Read entire file content:', data.toString()); });
Streams are better for big files to save memory.
Reading whole file is simpler but can crash if file is too big.
Use streams when you want to start processing data immediately.
Streams let you handle data in small pieces, saving memory.
Loading entire file reads all data at once, which can be slow or crash for big files.
Choose streams for big or continuous data, whole file reading for small files.
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
