Node.js — Streams
What are Streams?
Streams are objects for reading/writing data continuously.
Stream Types
| Type | Description |
|---|---|
| Readable | Source of data |
| Writable | Destination for data |
| Duplex | Both readable and writable |
| Transform | Modify data in transit |
Readable Stream
const fs = require('fs');
const readable = fs.createReadStream('file.txt', {
encoding: 'utf8',
highWaterMark: 16
});
readable.on('data', chunk => {
console.log(`Received ${chunk.length} bytes`);
});
readable.on('end', () => {
console.log('No more data');
});
Writable Stream
const writable = fs.createWriteStream('output.txt');
writable.write('Hello, ');
writable.write('World!\n');
writable.end();
Piping Streams
const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');
readable.pipe(writable);
Transform Stream
const { Transform } = require('stream');
const upperCase = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
process.stdin.pipe(upperCase).pipe(process.stdout);
Mini Practice
- Read a file with streams
- Write to a file with streams
- Pipe readable to writable
- Create a transform stream
Up Next
Continue with Buffers — binary data handling.
Related Topics
Frequently Asked Questions about Streams
What is Streams in Node.js?
Streams is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Streams?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Streams.
Why is Streams important in Node.js?
Streams is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.