Tips > Reliability & Performance

Compress Binary Data Before Storing or Transferring

Transferring large binary files between nodes, sending them as email attachments, or uploading to cloud storage is slow and bandwidth-intensive.

TipAdvanced1 min read

Transferring large binary files between nodes, sending them as email attachments, or uploading to cloud storage is slow and bandwidth-intensive. Add a compression step when the downstream consumer supports it.

Real-world example: A reporting workflow generates 15 CSV exports (2-10 MB each) and emails them to stakeholders. Without compression, the email is 80 MB and times out. With gzip, the total drops to 8 MB.

// Code node: Compress binary data
// Mode: Run Once for All Items
const zlib = require('zlib');

const results = [];

for (const item of $input.all()) {
  if (item.binary?.data) {
    const binaryData = await this.helpers.getBinaryDataBuffer(
      $input.all().indexOf(item),
      'data'
    );

    const compressed = zlib.gzipSync(binaryData);

    results.push({
      json: {
        ...item.json,
        originalSize: binaryData.length,
        compressedSize: compressed.length,
        compressionRatio: ((1 - compressed.length / binaryData.length) * 100).toFixed(1) + '%',
      },
      binary: {
        data: await this.helpers.prepareBinaryData(
          compressed,
          item.binary.data.fileName + '.gz',
          'application/gzip'
        ),
      }
    });
  } else {
    results.push(item);
  }
}

return results;
```text
For image-specific compression (e.g., resizing screenshots before emailing):

```javascript
// Using the Edit Image node instead of Code for image compression
// Edit Image node settings:
//   Operation: Resize
//   Width: 800
//   Height: (proportional)
//   Option > Quality: 75 (for JPEG)
```text

**Related:** [Flatten Deeply Nested API Responses](../code-node-mastery/01-flatten-deeply-nested-api-responses.md) | [Use Docker Compose with Health Checks for n8n and PostgreSQL](../self-hosting-operations/01-use-docker-compose-with-health-checks-for-n8n-and-postgresql.md)

Want this running in your stack?

I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.