Simple REST Server

Node.js Streams & Pipelines: Processing Gigabyte Files Without Memory Spikes

The Out-Of-Memory Trap: Why fs.readFile Fails in Production

A classic rite of passage for Node.js backend engineers is watching an otherwise stable production service crash with JavaScript heap out of memory. The culprit is almost always buffered I/O: attempting to load a 2 GB log dump, customer CSV export, or large video file into memory using fs.readFile() or res.send(data).

Because the V8 JavaScript engine enforces a default memory ceiling (~1.4 GB to 4 GB depending on architecture), buffering entire files into contiguous RAM buffers is fundamentally unscalable. The solution is Node.js Streams: processing data piece by piece as sequential chunks within a bounded buffer.

In this guide, we dive deep into readable, writable, and transform streams, demonstrate how to implement backpressure, and leverage stream/promises pipeline utilities to process gigabytes of data in a flat 30 MB memory footprint.


The 4 Stream Archetypes in Node.js

Stream TypeDirectionCore Events / MethodsPractical Production Example
ReadableSource $
ightarrow$ Consumer
data, end, pause(), resume()fs.createReadStream(), Incoming HTTP request
WritableConsumer $
ightarrow$ Destination
write(), drain, end()fs.createWriteStream(), HTTP ServerResponse
DuplexBidirectional (Read & Write)Independent read and write buffersTCP Net Sockets, TLS sockets
TransformDuplex with data modification_transform(), _flush()zlib.createGzip(), CSV parsers, encryptors

Understanding Backpressure: Preventing Consumer Overwhelm

Backpressure occurs when the data source reads chunks faster than the destination can write them. If you pipe data blindly without respecting buffer thresholds (highWaterMark), Node.js will buffer excess chunks in system RAM until the process runs out of memory.

Backpressure Mechanics:
┌─────────────────┐       fast flow      ┌──────────────────┐
│ ReadStream (Disk│ ═══════════════════► │ Buffer Queue     │
└─────────────────┘                      │ (highWaterMark)  │
                                         └────────┬─────────┘
                                                  │ slow write
                                                  ▼
                                         ┌──────────────────┐
                                         │ Writable (Network│
                                         └──────────────────┘
When buffer reaches capacity (returns false), ReadStream must PAUSE.
When Writable clears buffer ('drain' event), ReadStream RESUMES.

Production Pipeline: Transforming a 5GB CSV to JSON

Never chain streams manually with readable.pipe(writable) in production. pipe() does not properly forward errors or automatically clean up file descriptors when an intermediate stream fails. Always use stream/promises.pipeline:

// process-csv.js
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
import zlib from 'node:zlib';
import { Transform } from 'node:stream';

// Custom Transform Stream: CSV line to JSON object
class CsvToJsonTransform extends Transform {
  constructor(options = {}) {
    super({ ...options, objectMode: true });
    this.headers = null;
    this.buffer = '';
  }

  _transform(chunk, encoding, callback) {
    this.buffer += chunk.toString();
    const lines = this.buffer.split('\n');
    
    // Retain incomplete last line in buffer
    this.buffer = lines.pop();

    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed) continue;

      if (!this.headers) {
        this.headers = trimmed.split(',');
      } else {
        const values = trimmed.split(',');
        const record = {};
        this.headers.forEach((h, i) => {
          record[h] = values[i];
        });
        this.push(JSON.stringify(record) + '\n');
      }
    }
    callback();
  }

  _flush(callback) {
    if (this.buffer.trim() && this.headers) {
      const values = this.buffer.trim().split(',');
      const record = {};
      this.headers.forEach((h, i) => {
        record[h] = values[i];
      });
      this.push(JSON.stringify(record) + '\n');
    }
    callback();
  }
}

async function processBigData() {
  console.time('Processing Pipeline');

  try {
    await pipeline(
      fs.createReadStream('input_large_dataset.csv', { highWaterMark: 64 * 1024 }),
      new CsvToJsonTransform(),
      zlib.createGzip(),
      fs.createWriteStream('output_compressed.json.gz')
    );
    console.log('Pipeline executed successfully with flat memory profile!');
  } catch (err) {
    console.error('Pipeline failed with error:', err.message);
  } finally {
    console.timeEnd('Processing Pipeline');
  }
}

processBigData();

Streaming HTTP Responses Directly to Clients

When generating large reports or file downloads in an Express/Node.js API, stream the response straight to the client socket rather than building strings in memory:

// server.js
import express from 'express';
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';

const app = express();

app.get('/download/audit-logs', async (req, res) => {
  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', 'attachment; filename="audit_logs.csv"');

  const sourceStream = fs.createReadStream('/var/log/app/audit.log');

  try {
    await pipeline(sourceStream, res);
  } catch (err) {
    // If headers haven't sent yet, send 500
    if (!res.headersSent) {
      res.status(500).json({ error: 'Stream transfer aborted' });
    }
  }
});

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

Frequently Asked Questions (FAQ)

What is the default highWaterMark in Node.js streams?

For standard byte streams (like fs.createReadStream), the default highWaterMark is 64 kB. For streams operating in objectMode (like transform streams emitting JavaScript objects), the default is 16 objects.

What is the difference between pipeline() and pipe()?

pipe() only handles data flow and does not safely handle errors across intermediate transform steps. If an error occurs in a middle stream, the source and destination streams remain open, leaking memory and sockets. pipeline() automatically closes all streams and rejects a Promise if any step fails.

Can I iterate through a stream using for-await-of?

Yes. Node.js readable streams implement the AsyncIterator protocol. You can cleanly loop through chunks using for await (const chunk of stream), making stream consumption read like standard synchronous loops with native try/catch error handling.


Continue expanding your technical depth with our related engineering guides:

Published by Mohit Kumar under NodeJS Mastery. Learn more in our deep-dive on The Node.js Event Loop Architecture.

Authoritative Reference: Consult the Node.js Official Stream API Reference for normative standards and release specifications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top