Node.js

What Is the Difference Between Streams and Buffers in Node.js?

When working with files, videos, large datasets, or network requests in Node.js, you may encounter two important concepts: Streams and Buffers.Both help…

D
DevByteTechnical Author
Published
13 min read2 views
What Is the Difference Between Streams and Buffers in Node.js?

When working with Node.js, you will often need to read files, upload images, download documents, process videos, or transfer data between a client and a server. These operations might look simple when you're working with small amounts of data, but things can become complicated when the files get larger.

Imagine you're building a Node.js application where users can upload videos. One video might be 5 MB, while another could be 500 MB. If your application tries to load the entire video into memory before processing it, you could end up using a significant amount of RAM.

This is where buffers and streams in Node.js become important.

Both are used when working with data, but they solve different problems. A buffer stores binary data in memory, while a stream allows data to be processed gradually as it becomes available.

I think the easiest way to understand the difference is to look at how Node.js handles real files rather than learning definitions alone.

In this guide, we'll explore buffers and streams, understand how they work, and look at practical examples you can use in your own Node.js projects.

What Is a Buffer in Node.js?

A buffer in Node.js is an object used to work with binary data directly in memory.

Computers store files as bytes. Whether you're working with an image, a PDF, an audio file, or a video, the underlying data is represented as a sequence of bytes.

Node.js provides the built-in Buffer class to create, store, and manipulate these bytes.

For example, suppose you want to create a buffer containing the word Hello.

const buffer = Buffer.from("Hello");

console.log(buffer);
console.log(buffer.toString());

Output:

<Buffer 48 65 6c 6c 6f>
Hello

The first output displays the hexadecimal representation of the bytes. The second converts the buffer back into a readable string.

Each byte represents part of the original data.

You might wonder why Node.js needs buffers when JavaScript already supports strings and arrays.

The reason is that strings are designed primarily for text, whereas buffers are useful for handling raw binary data. This matters when working with files, network protocols, images, and other data that cannot be treated as ordinary text.

When Should You Use a Buffer?

Buffers are useful when you need to work with a manageable amount of binary data in memory.

For example, you might use a buffer when:

  • Reading a small configuration file.

  • Processing a small image uploaded by a user.

  • Converting binary data into a Base64 string.

  • Working with data received from a network request.

  • Preparing a small file before sending it to another service.

However, storing an entire large file in a buffer can consume considerable memory.

Let's see what that looks like in a practical example.

Reading a File Into a Buffer

Node.js provides the built-in fs module for working with files.

One common method is fs.readFile(), which reads a file and provides its contents when the operation finishes.

Consider this example:

const fs = require("node:fs");

fs.readFile("example.txt", (err, data) => {
    if (err) {
        console.error("Error reading file:", err);
        return;
    }

    console.log(data);
    console.log(data.toString());
});

If example.txt contains:

Learning Node.js is interesting!

The data argument will normally be a Buffer because no text encoding was specified.

Calling data.toString() converts the buffer into a string.

This is perfectly reasonable for a small text file. But imagine using the same approach to read a multi-gigabyte video file.

The application would need to allocate enough memory to hold the file contents before the callback receives the completed data. That can create unnecessary memory pressure.

For large files, streams are often a better choice.

What Is a Stream in Node.js?

A stream is an interface for handling data piece by piece rather than requiring the entire dataset to be available at once.

Instead of reading a complete file into memory, a stream can read smaller chunks and make them available as the operation progresses.

Think about watching a video online.

You don't normally have to download the entire video before playback can begin. The video player receives data progressively and can start playing once enough data is available.

Node.js streams follow a similar idea: data can be consumed as it becomes available.

Streams are particularly useful when working with:

  • Large files.

  • HTTP requests and responses.

  • File uploads and downloads.

  • Video and audio processing.

  • Data compression.

  • Data transformations.

  • Continuous data sources.

Node.js includes several types of streams, each designed for a different purpose.

Let's understand them before moving to practical examples.

1. Readable Streams

A readable stream is used to read data from a source.

For example, you can create a readable stream from a file using fs.createReadStream().

const fs = require("node:fs");

const readStream = fs.createReadStream("example.txt");

readStream.on("data", (chunk) => {
    console.log("Received chunk:", chunk.toString());
});

readStream.on("end", () => {
    console.log("Finished reading the file.");
});

readStream.on("error", (err) => {
    console.error("Error:", err);
});

Here, Node.js reads the file in chunks and emits a data event as chunks become available.

The end event indicates that the readable stream has no more data to provide.

The error event lets you handle errors that occur while reading the file.

By default, a file read stream typically produces Buffer chunks unless an encoding is configured.

2. Writable Streams

A writable stream is used to write data to a destination.

For example, you can create a writable stream to save data into a file.

const fs = require("node:fs");

const writeStream = fs.createWriteStream("output.txt");

writeStream.write("Hello from Node.js!\n");
writeStream.write("This is a writable stream.\n");

writeStream.end();

writeStream.on("finish", () => {
    console.log("File writing completed.");
});

writeStream.on("error", (err) => {
    console.error("Error writing file:", err);
});

This example writes two lines into output.txt.

The end() method signals that no more data will be written. The finish event fires after all data has been flushed to the underlying system.

Writable streams are useful when generating reports, writing logs, saving downloaded files, or processing large datasets.

3. Duplex Streams

A duplex stream supports both reading and writing.

In other words, it can receive data and send data independently.

A network socket is a common example. Your application can receive information from another computer and send information back through the same connection.

Duplex streams are useful in network communication and other situations where two-way data transfer is required.

4. Transform Streams

A transform stream is a type of duplex stream that transforms data as it passes through.

For example, Node.js provides compression streams through its built-in zlib module.

You can read a file, compress its contents, and write the compressed result without loading the entire file into memory.

Transform streams are also useful for encryption, data conversion, and processing pipelines.

The Main Difference Between Streams and Buffers

Now that we understand both concepts, let's compare them directly.

The biggest difference is how data is handled in memory.

A buffer represents a collection of bytes held in memory. A stream provides a way to process data incrementally.

Feature

Buffer

Stream

Main purpose

Stores binary data in memory

Processes data incrementally

Data handling

Works with a collection of bytes

Works with data as it becomes available

Memory usage

Depends on the amount of data stored

Can reduce memory requirements for large datasets

Suitable for

Small files and manageable binary data

Large files and continuous data transfer

Processing

Often used when data is already available

Can process data before the entire source is read

Examples

Buffer.from(), Buffer.alloc()

fs.createReadStream(), fs.createWriteStream()

Common use cases

Small uploads, binary transformations

File transfer, compression, HTTP communication

One important detail: streams don't eliminate buffers.

In Node.js, readable streams commonly deliver data in Buffer chunks. A stream is the mechanism for processing the data incrementally, while a buffer is one possible representation of each chunk.

Understanding this distinction makes the relationship between the two concepts much easier to remember.

Practical Example: Reading a Large File Using a Stream

Let's say you're building a backend application that needs to process a large log file.

The file contains millions of lines, and you want to count how many lines it has.

Reading the entire file into memory would be unnecessary because you only need to process it line by line.

Node.js streams can help you handle this efficiently.

First, install the readline module? You don't need to install anything. The readline module is built into Node.js.

Here's an example:

const fs = require("node:fs");
const readline = require("node:readline");

async function countLines() {
    const fileStream = fs.createReadStream("large-log.txt");

    const lineReader = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    let totalLines = 0;

    for await (const line of lineReader) {
        totalLines++;
    }

    console.log("Total lines:", totalLines);
}

countLines().catch(console.error);

Let's understand what happens here.

First, fs.createReadStream() creates a readable stream for the file.

Next, readline.createInterface() processes the incoming text and exposes individual lines.

The for await...of loop consumes those lines one at a time, incrementing the counter for each line.

Finally, the program prints the total number of lines.

This approach avoids storing the entire file contents in a single Buffer.

It doesn't mean memory usage will remain exactly constant under every condition, but it can substantially reduce memory requirements compared with reading the whole file at once.

For log processing, CSV imports, and other large text files, this pattern is particularly useful.

Practical Example: Copying a Large File Using Streams

Another common use case is copying a file from one location to another.

You could read the source file completely and then write its contents to the destination. However, that approach may require a large amount of memory.

A stream-based approach is simpler.

const fs = require("node:fs");

const source = fs.createReadStream("large-video.mp4");
const destination = fs.createWriteStream("video-copy.mp4");

source.on("error", (err) => {
    console.error("Error reading source:", err);
});

destination.on("error", (err) => {
    console.error("Error writing destination:", err);
});

destination.on("finish", () => {
    console.log("File copied successfully!");
});

source.pipe(destination);

The pipe() method connects the readable stream to the writable stream.

As the source produces chunks, the destination writes them to the new file.

This is much more memory-friendly than loading the entire video into a single Buffer before writing it.

The pipe() method also coordinates data flow so that a fast source doesn't overwhelm a slower destination. This is related to a stream feature called backpressure, which we'll discuss shortly.

For ordinary file copying, Node.js also provides fs.copyFile(), which may be the simpler choice. The stream example is useful when you need to understand how streaming works or build a more complex processing pipeline.

Practical Example: Sending a File Through an Express API

Streams are also important when building APIs with Node.js and Express.

Suppose you have a PDF report stored on your server and want users to download it.

You can create a readable stream and pipe it into the HTTP response.

const express = require("express");
const fs = require("node:fs");
const path = require("node:path");

const app = express();

app.get("/download-report", (req, res, next) => {
    const filePath = path.join(__dirname, "reports", "report.pdf");

    const fileStream = fs.createReadStream(filePath);

    fileStream.on("error", (err) => {
        if (res.headersSent) {
            res.destroy(err);
        } else {
            next(err);
        }
    });

    res.setHeader(
        "Content-Disposition",
        'attachment; filename="report.pdf"'
    );

    res.setHeader("Content-Type", "application/pdf");

    fileStream.pipe(res);
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

When a user requests /download-report, the server reads the PDF in chunks and sends those chunks through the HTTP response.

This is helpful when serving large files because the application doesn't need to load the complete PDF into a single Buffer first.

For production applications, you should also handle client disconnections and other response lifecycle issues appropriately.

A useful security reminder: If users can choose which file to download, don't directly combine their input with a filesystem path. Restrict file access to an approved directory and verify authorization before serving sensitive files.

What Is Backpressure in Node.js Streams?

Backpressure is an important concept when working with streams.

Imagine you're downloading a large file from a server. The source can produce data quickly, but your destination disk writes data more slowly.

If the source continues producing data without considering the destination's capacity, the application may accumulate too much data in memory.

Backpressure helps regulate this flow.

When a writable stream's internal buffer reaches its high-water mark, its write() method can return false. This indicates that the producer should stop writing temporarily and wait for the writable stream's drain event before continuing.

Here's a simplified example:

const fs = require("node:fs");

const writeStream = fs.createWriteStream("output.txt");

for (let i = 0; i < 10000; i++) {
    const canContinue = writeStream.write(`Line ${i}\n`);

    if (!canContinue) {
        console.log("The writable stream needs time to catch up.");
        break;
    }
}

writeStream.end();

This example demonstrates how a writable stream can signal backpressure, but it doesn't implement a complete solution for writing all 10,000 lines. It stops after the first write() call that returns false.

In real applications, you need to resume writing after the drain event or use an API such as stream.pipeline() that manages stream flow for you.

For example, pipeline() is generally a good choice when connecting streams because it handles errors and stream cleanup more reliably than manually wiring several events.

Understanding backpressure becomes particularly important when processing large uploads, streaming API responses, or transferring files between services.

Can You Convert a Buffer Into a Stream?

Yes. You can create a readable stream from a Buffer.

This can be useful when you already have binary data in memory but want to pass it into an API that expects a stream.

For example:

const { Readable } = require("node:stream");

const buffer = Buffer.from("Hello from a buffer!");

const readableStream = Readable.from(buffer);

readableStream.on("data", (chunk) => {
    console.log(chunk.toString());
});

readableStream.on("end", () => {
    console.log("Stream completed.");
});

Because a Buffer is iterable, Readable.from(buffer) treats its iterable values as stream items. In this case, the emitted chunks are individual byte values rather than one Buffer containing the complete string.

If you want to stream the entire Buffer as a single chunk, you can instead use:

const { Readable } = require("node:stream");

const buffer = Buffer.from("Hello from a buffer!");

const readableStream = Readable.from([buffer]);

readableStream.on("data", (chunk) => {
    console.log(chunk.toString());
});

Here, the array contains one Buffer, so the stream emits that Buffer as a single chunk.

Keep in mind that converting a Buffer into a stream doesn't make the original data disappear from memory. The Buffer still exists, so this technique doesn't provide the same memory advantages as reading a large file directly through a stream.

When Should You Use Buffers and When Should You Use Streams?

The right choice depends on what your application needs to do.

Use a Buffer when you need to hold a manageable amount of binary data in memory, inspect its contents, or perform an operation that requires the complete data to be available.

Use a stream when you want to process data gradually, especially when the source may contain a large amount of data.

For example:

Use a Buffer when:

  • Converting a small string into binary data.

  • Processing a small image that is already in memory.

  • Handling a small binary message.

  • Preparing data for an API that expects a Buffer.

Use a Stream when:

  • Reading a large video file.

  • Downloading a large document.

  • Processing millions of lines in a log file.

  • Compressing files without loading them completely into memory.

  • Transferring data between an HTTP request and a file.

There is no rule that says buffers are bad and streams are always better. Both are useful, and the right approach depends on the data size, memory requirements, and APIs you're working with.

Final Thoughts

Buffers and streams are fundamental concepts in Node.js, especially when you're building backend applications that handle files or transfer data.

A Buffer stores binary data in memory, while a stream allows data to be processed incrementally. Streams commonly work with Buffer chunks, so the two concepts are closely related rather than competing technologies.

If you're just starting with Node.js, begin by experimenting with Buffer.from(), fs.readFile(), and fs.createReadStream(). Then try copying a large file, reading a log file line by line, and sending a file through an Express API.

These examples will help you understand why streams are useful beyond simply memorizing their definitions.

As your applications grow, knowing when to use a Buffer and when to use a stream can help you manage memory more effectively and build more reliable Node.js services.

For further reading, check the official Node.js Buffer documentation and Node.js Streams documentation.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘