</>
Skip to content
Node.js lessons (20/44)

Node.js — Streams

What are Streams?

Streams are objects for reading/writing data continuously.

Stream Types

TypeDescription
ReadableSource of data
WritableDestination for data
DuplexBoth readable and writable
TransformModify 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

  1. Read a file with streams
  2. Write to a file with streams
  3. Pipe readable to writable
  4. 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.