Skip to content
New: a free website for your business, live in 48 to 72 hoursWorkflow automation on n8n and Claude, built for your businessFixed price, agreed before we start · Live in 5 to 10 business days30-day money-back guarantee on every planProfessional firms · Agencies · E-commerceYou own every workflow, in your own n8nClaude API: your data is not used for trainingHuman approval on every sensitive stepFree automation audit, no obligation
PURIST
30 days
Money-back window
14 h/wk
Modeled time saved
99.97%
Uptime SLA
< 7 days
Deploy time
PURIST AI
Claude Opus 4.7 · n8n v1.71 · <80ms
What type of business are you running? I'll show you exactly which processes we'd automate first and your estimated ROI.
Powered by n8n + Claude Opus 4.7 Get my free automation plan →
n8n Code Node Binary Data: Read, Change and Return Files
Guides 7 min read · 1,548 words

n8n Code Node Binary Data: Read, Change and Return Files

How binary data is structured in n8n, the documented way to read a file buffer in the Code node, and copy-paste patterns to edit, rename and return files.

Steve, founder of PURIST

November 6, 2026

PURIST: Stuck on n8n? Our n8n experts fix and build workflows like this one, at a fixed price →

Files in n8n (PDFs, images, CSV exports, audio) travel as binary data next to the usual JSON. The Code node can read and change them, but only through the right helper. Old forum snippets that read items[0].binary.data.data directly break on current versions, because n8n may store the file outside the item. Here is the method the documentation recommends, and the patterns built on it.

In short. Read a file with await this.helpers.getBinaryDataBuffer(itemIndex, 'data'), which returns a Node.js Buffer. Change the file name or MIME type by editing item.binary.data.fileName and mimeType. To create a new file from text or JSON, the Convert to File node is usually simpler than code. Binary helpers are not available in Python.

n8n Code Node Binary Data: Read, Change and Return Files: workflow diagram
A file travels next to the JSON under a binary key; the Code node reads it with getBinaryDataBuffer(). Illustration: PURIST.

How binary data looks in an item

An item that carries a file has two parts: json for regular fields and binary for files, keyed by a property name. Most nodes use data as the default name.

javascript
{
  json: { orderId: 812 },
  binary: {
    data: {
      fileName: 'invoice-812.pdf',
      mimeType: 'application/pdf',
      fileExtension: 'pdf',
      // the content itself, or a reference to where n8n stores it
    },
  },
}

Depending on your configuration, n8n keeps file contents in memory or on disk, so never assume the content sits in the item. That is why the helper exists.

Read the file content

The documented method returns the content as a Buffer for any item and binary property:

javascript
// Mode: Run Once for All Items
const buffer = await this.helpers.getBinaryDataBuffer(0, 'data');
const text = buffer.toString('utf8');
return [{ json: { length: buffer.length, preview: text.slice(0, 200) } }];

The first argument is the item index, the second the binary property name. The documentation is explicit that you should always use this function and avoid the older items[0].binary.data.data approach.

n8n Code Node Binary Data: Read, Change and Return Files: node settings
Editing a CSV in the Code node and returning it as a new file. Illustration: PURIST.

Example: add a header row to a CSV

javascript
const out = [];
const items = $input.all();
for (let i = 0; i < items.length; i++) {
  const buffer = await this.helpers.getBinaryDataBuffer(i, 'data');
  const csv = 'email,company,source\n' + buffer.toString('utf8');
  out.push({
    json: items[i].json,
    binary: {
      data: {
        data: Buffer.from(csv, 'utf8').toString('base64'),
        mimeType: 'text/csv',
        fileName: items[i].binary.data.fileName || 'export.csv',
      },
    },
  });
}
return out;

Returning binary content as a base64 string in data, with mimeType and fileName, is the standard item format that the next nodes read.

Example: hash a file

Useful to detect duplicates or prove a document did not change. crypto is available in the Code node, on Cloud as well.

javascript
const crypto = require('crypto');
const out = [];
const items = $input.all();
for (let i = 0; i < items.length; i++) {
  const buffer = await this.helpers.getBinaryDataBuffer(i, 'data');
  const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
  out.push({ json: { ...items[i].json, sha256 }, binary: items[i].binary });
}
return out;

Keep binary: items[i].binary in the output if later nodes still need the file. A Code node only passes on what it returns.

Example: rename a file before uploading it

The HTTP Request node uses the binary file name, not the form field name, when it sends multipart data. The documentation gives this exact fix:

javascript
for (const item of $input.all()) {
  item.binary.data.fileName = 'index.html';
}
return $input.all();

Set item.binary.data.mimeType too if the receiving API checks the content type.

When to skip the Code node

JobBetter tool
Turn JSON or text into a fileConvert to File node
Read a CSV, XLSX or PDF into fieldsExtract from File node
Download a file from a URLHTTP Request node, Response Format = File
Upload a file to an APIHTTP Request node, Form-Data with an n8n Binary File field
Zip or unzipCompression node

Use code for what those nodes cannot do: custom parsing, merging files, checks and hashes.

Limits to know

  • getBinaryDataBuffer() is not supported in Python.
  • Large files use memory when you load the whole buffer. Process big exports in batches or let dedicated nodes stream them.
  • On n8n Cloud there is no file system access from the Code node. Use the file nodes instead.

Worked example: merge several CSV exports into one file

Your accounting tool exports one CSV per store, and you want one combined file for the weekly report. Each item from the previous node carries one CSV in binary.data.

javascript
const items = $input.all();
let header = null;
const rows = [];
for (let i = 0; i < items.length; i++) {
  const buf = await this.helpers.getBinaryDataBuffer(i, 'data');
  const lines = buf.toString('utf8').split(/\r?\n/).filter(Boolean);
  if (!lines.length) continue;
  if (!header) header = lines[0];
  rows.push(...lines.slice(1));
}
const csv = [header, ...rows].join('\n');
return [{
  json: { files: items.length, rows: rows.length },
  binary: { data: {
    data: Buffer.from(csv, 'utf8').toString('base64'),
    mimeType: 'text/csv',
    fileName: `weekly-${$now.toFormat('yyyy-LL-dd')}.csv`,
  } },
}];

The output is one item with a summary in json and the merged file in binary. Send it with an email node or upload it to storage. This approach assumes all exports share the same header; check that before combining files from different sources.

How n8n stores binary data

n8n can keep file contents in memory or write them to disk (and, on some setups, external storage), depending on the instance configuration. In memory mode the content may sit in the item; in filesystem mode the item only holds a reference. Code that reads item.binary.data.data directly therefore works on one instance and fails on another. getBinaryDataBuffer() hides that difference, which is why the documentation insists on it.

Binary data also counts toward execution data. Large files kept on many items make executions heavy to store and to open in the editor. Drop files you no longer need by returning items without binary once a file has been uploaded.

Text, base64 and encodings

You haveYou wantCode
BufferUTF-8 textbuf.toString('utf8')
TextBufferBuffer.from(text, 'utf8')
BufferBase64 for an item or an APIbuf.toString('base64')
Base64 from an APIBufferBuffer.from(b64, 'base64')
Text from an old Windows exportCorrect charactersbuf.toString('latin1')

Troubleshooting table

SymptomLikely causeFix
"No binary data property 'data' exists"File stored under another keyCheck the Binary tab of the input, use that name
File arrives empty downstreamOutput item lost its binaryPass binary through in the returned item
Strange characters (é becomes é)Wrong text encodingDecode with the right encoding, often latin1
Upload API rejects the fileMissing file name or MIME typeSet fileName and mimeType
Execution is very slow to openMany large files kept on itemsDrop binary after use; process in batches

Common mistakes to avoid

  • Assuming data is always the property name. Some nodes let users rename it.
  • Holding hundreds of files in one execution. Loop in batches and upload as you go.
  • Base64 files inside JSON bodies when the API accepts multipart. Base64 adds about a third to the size; multipart is lighter.

Production checklist

  • Binary read with getBinaryDataBuffer(), never from the item directly.
  • binary passed on in the output when later nodes need the file.
  • File name and MIME type set explicitly before uploads.
  • Large files processed in batches to keep memory stable.

Frequently asked questions

How do I get the binary data in an n8n Code node?

Use await this.helpers.getBinaryDataBuffer(itemIndex, 'propertyName'). It returns a Buffer you can read with .toString() or pass to crypto.

Why is item.binary.data.data empty or wrong?

n8n may store binary content outside the item, depending on the binary data mode. Reading the property directly is not reliable. Use getBinaryDataBuffer().

How do I return a file from a Code node?

Return an item with a binary object: a property (usually data) containing base64 data, a mimeType and a fileName. For simple text or JSON files, the Convert to File node does it without code.

Can I use binary data in a Python Code node?

getBinaryDataBuffer() is not available in Python. Handle files with the dedicated nodes, or use JavaScript for that step.

How do I convert a binary file to text in the n8n Code node?

Read it with await this.helpers.getBinaryDataBuffer(index, 'data'), then call .toString('utf8') on the Buffer.

How do I create a PDF or image in the Code node?

The Code node is not a renderer. Generate files with a dedicated service or node (for example an HTML to PDF API through the HTTP Request node), then handle the result as binary.

How large can files be in n8n?

It depends on memory and the binary data mode of your instance. Webhooks accept 16 MB by default (N8N_PAYLOAD_SIZE_MAX on self-hosted).

Tags

n8ncode nodebinary datafilescsv
Steve, founder of PURIST

Steve founded PURIST, a workflow automation studio working with n8n, Make and Claude AI, and is the point of contact on every project. Prices and features in our articles come from vendor documentation and public pricing pages. How we research and score tools.

Complete guide

Automation Tools & Platforms

11 min read n8n Code Node: 15 JavaScript Examples You Can Copy and … 8 min read n8n Code Node With Multiple Inputs: 3 Methods That Work 7 min read Fix "Cannot find module" in the n8n Code Node (npm Pack… 7 min read n8n Code Node Errors Fixed: "Code doesn't return items … 7 min read $env and Credentials in the n8n Code Node: What Works a… 7 min read Python in the n8n Code Node (n8n 2.x): Setup, Syntax an… 7 min read Fix n8n "The requested webhook is not registered" (Test… 6 min read n8n Webhook URL: Test vs Production, and How to Change … 7 min read n8n Respond to Webhook: Return JSON, Status Codes, Redi… 8 min read Secure an n8n Webhook: Header Auth, Basic Auth, JWT and… 7 min read n8n Webhook Not Working? 10 Causes and How to Fix Each … 7 min read n8n HTTP Request Pagination: Every Pattern With Working… 7 min read n8n HTTP Request Authentication: API Keys, Bearer Token… 7 min read n8n HTTP Request Timeout and "Aborted" Errors: Causes a… 7 min read Upload and Download Files With the n8n HTTP Request Nod… 6 min read Fix ECONNREFUSED in n8n: Docker, localhost and 127.0.0.… 6 min read n8n 429 Too Many Requests: Batching, Retries and Rate L… 6 min read Fix redirect_uri_mismatch for n8n OAuth2 Credentials (G… 7 min read n8n Expression Errors Fixed: "Referenced node is unexec… 6 min read Anatomy Claude skill: what it is, how to install it, an… 5 min read How to explain a business process with the Anatomy skil… 5 min read Anatomy vs Mermaid vs Excalidraw: which to explain a wo… 14 min read n8n LinkedIn Job Automation: Auto-Apply, Track, and Fol… 16 min read n8n HTTP Request Node: Complete Documentation and Examp… 18 min read The future of automation: how our engineering team is s… 8 min read n8n vs Make vs Zapier: the honest comparison your busin… 11 min read n8n vs Make vs Zapier: an honest comparison for product… 7 min read Webhook vs polling: the architecture decision that dete… 24 min read n8n tutorial: build your first production workflow in u… 26 min read The 9 best Zapier alternatives in 2026: an honest ranki… 21 min read Make.com tutorial: build powerful automations without c… 19 min read Automation consultant vs DIY: how to decide what is rig… 14 min read n8n Self-Hosted vs Cloud: The Complete Decision Guide (… 15 min read 5 Zapier Free Alternatives That Handle Real Production … 15 min read WhatsApp Business Automation With n8n: Build a 24/7 Cus… 17 min read Google Workspace Automation: 15 Workflows for Sheets, D… 16 min read Claude AI for Business Automation: What It Does, What I… 15 min read Airtable Automation With n8n: 10 Workflows That Make Yo… 15 min read Droven.io AI Automation Tools: Full Review and Best Alt… 14 min read Droven.io RPA and Business Automation: An Honest 2026 R… 15 min read Enterprise Workflow Automation: The Complete Guide for … 13 min read Document Workflow Automation: Software, Implementation,… 14 min read Marketing Automation Workflow: From Content Creation to… 16 min read Ad Campaign Workflow Data Model and SDR Inbound Pipelin… 14 min read ComfyUI Workflows for Business: Product Photography, Ma… 13 min read GPT-5.2 for Business Workflows and the spec-workflow-mc… 17 min read ServiceNow vs IBM BAW vs n8n: Enterprise Workflow Autom… 16 min read 9 Best Workflow Automation Tools for Small Business in …

Keep reading

More from the blog.

All articles

From audit to deployment

Experience the automation
these articles are about.

Get my free automation plan →