К основному содержанию
скилл CX Codex

n8n-binary-and-data-official — скилл для Claude Code: файлы

Скилл объясняет, как в n8n устроена работа с файлами, картинками и вложениями и почему бинарные данные не проходят через инструменты агента.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add n8n-io/skills --skill n8n-binary-and-data-official -a claude-code
Открыть на GitHub

Что делает n8n-binary-and-data-official

В n8n у каждого элемента два слота: $json с обычными данными и $binary с файлами. Скилл настаивает на простом правиле: содержимое файла лежит в $binary, а не в $json, и попытка прочитать его оттуда — типичная ошибка. Для записи бинарных данных в Code-узле показан возврат объекта с полем binary, где data — base64, плюс mimeType и fileName.

Отдельный блок посвящён инструментам агента. Параметры и результаты там только JSON, поэтому бинарные данные не пересекают эту границу ни в одну сторону. Входящий файл сначала кладут в хранилище, а в инструмент через fromAi() передают ключ; исходящий файл загружают в хранилище и возвращают ссылку в JSON. Флаг passthroughBinaryImages: true даёт модели увидеть картинку, но инструментам доступа к ней не даёт — это повод проверить свою схему, если вы рассчитывали на обратное.

Ещё две темы: сохранение бинарных данных после JSON-преобразования через узел Merge и требование к хранилищу с публичным URL, когда картинку нужно показать в чате вроде Slack или Telegram. Хранилище настраивает пользователь, в n8n его нет. Внутри скилла четыре справочных файла: references/BINARY_BASICS.md, references/AGENT_TOOL_BINARY.md, references/MERGE_FOR_CONTEXT.md и references/CDN_REQUIREMENT.md.

Какие задачи решает

  • прочитать содержимое файла из $binary, а не из $json
  • собрать бинарные данные в Code-узле и вернуть их дальше по workflow
  • передать загруженный пользователем файл в инструмент агента через ключ в хранилище
  • вернуть из инструмента ссылку на сгенерированный файл вместо сырых байтов
  • не потерять вложение после JSON-преобразования в узле Merge

Примеры запросов агенту

  • Почему мой Code-узел не видит файл из предыдущего шага? Проверь, что я читаю $binary, а не $json.
  • Мне нужно, чтобы инструмент агента принял загруженную картинку. Покажи схему с предварительной загрузкой в хранилище и передачей ключа через fromAi().
  • После Edit Fields пропало вложение. Как собрать его обратно через Merge?

Как установить n8n-binary-and-data-official

1Через Skills CLI (Vercel)

npx skills add n8n-io/skills --skill n8n-binary-and-data-official -a claude-code

2Вручную: положить файлы

~/.claude/skills/n8n-binary-and-data-official/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/n8n-binary-and-data-official/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о n8n-binary-and-data-official

Как установить n8n-binary-and-data-official в Claude?

Выполните npx skills add n8n-io/skills --skill n8n-binary-and-data-official -a claude-code. После этого файл скилла появится по пути ~/.claude/skills/n8n-binary-and-data-official/SKILL.md.

Что делает n8n-binary-and-data-official?

Разбирает работу с файлами и бинарными данными в n8n: слот $binary, генерацию и чтение бинарных данных в Code-узле, передачу файлов в инструменты агента и вывод картинок в чат.

Почему инструмент агента не получает загруженный файл?

Параметры и результаты инструментов — только JSON, поэтому бинарные данные через эту границу не проходят. Флаг passthroughBinaryImages: true влияет лишь на то, что видит модель, и не открывает файл инструментам.

Исходный текст

SKILL.md · Apache-2.0
---
name: n8n-binary-and-data-official
description: Use when handling files, images, attachments, or binary data in n8n, OR when an AI agent needs to take a user-uploaded file as tool input or return a generated file. For Data Tables (schemas, dedup, persistent state), see the separate n8n-data-tables-official skill. Triggers on "file", "image", "PDF", "attachment", "binary", "upload", "download", chat trigger with files, agent tool that needs a file, vision/multimodal, or any handling of non-JSON file data.
---

# n8n Binary and Data

n8n handles two kinds of data: JSON (in `$json`) and binary (in `$binary`), flowing side-by-side. Binary has sharp edges around agent tools, storage, and display contexts (chat surfaces, message rendering).

For tabular storage (Data Tables), see the **`n8n-data-tables-official`** skill.

## Non-negotiables

1. **Binary is in `$binary`, not `$json`.** Don't read file contents from `$json`.
2. **Binary cannot cross the agent tool boundary in either direction.** Tool parameters are JSON only (via `fromAi()`), and tool results are JSON only. Pre-stage binary in storage and pass keys/URLs through JSON. The agent's `passthroughBinaryImages: true` lets the LLM *see* uploaded images for vision, but it does NOT enable tools to receive them. See `references/AGENT_TOOL_BINARY.md`.

## Strong defaults

- **Merge nodes keep binary in context.** When a side computation strips binary, merge it back rather than re-fetching. See `references/MERGE_FOR_CONTEXT.md`.

## Binary basics

In n8n, each item has two slots:

```ts
{
    json: { ... },           // your data
    binary: {                // your files
        data: {              // 'data' is the typical key; can be any name
            data: '<base64>',
            mimeType: 'application/pdf',
            fileName: 'invoice.pdf',
            fileExtension: 'pdf',
        },
    },
}
```

`$binary.<key>` reads the named property. Most file-handling nodes have a `binaryPropertyName` parameter, the key inside `$binary`.

### Setting binary

File-producing nodes (HTTP Request with binary response, Read Files, etc.) populate `$binary` automatically. To produce binary in a Code node:

```ts
return [{
    json: { ... },
    binary: {
        data: {
            data: Buffer.from(content).toString('base64'),
            mimeType: 'text/plain',
            fileName: 'output.txt',
        },
    },
}]
```

### Reading binary

```ts
// In a Code node
const buffer = await this.helpers.getBinaryDataBuffer(0, 'data')
const text = buffer.toString('utf-8')
```

Most workflows don't need to read binary directly. Pass it through to consumer nodes (email attachments, file uploads, etc.).

See `references/BINARY_BASICS.md` for more.

## Agent tool gymnastics

Agent tools (sub-workflows wired into an AI Agent node or a first-class n8n Agent, or workflows exposed as MCP tools) have a constraint: parameters and results are JSON, not binary. Affects both directions.

**Inbound (user uploads → tool consumes):** the chat trigger gives `files[]`. The agent can have `passthroughBinaryImages: true` for vision, but `fromAi()` can't pass binary to a tool. So:

1. Pre-stage uploaded files: hash a key, upload to private storage.
3. The tool's `fromAi('imageName', '...', 'string')` receives the key. The sub-workflow downloads from storage.

**Outbound (tool produces → agent returns):** a tool generates a file. It can't return raw binary.

1. Generate binary internally.
2. Upload to storage, get back URL/key.
3. Return JSON: `{ ok: true, file_id: '...', url: '...' }`.
4. The agent embeds the URL in its response, or another tool fetches by key.

For the full pattern including the async-via-webhook variant for long-running tools, see `references/AGENT_TOOL_BINARY.md`.

## Merge for keeping binary in context

A JSON-only operation (Edit Fields, Code, IF) often strips binary from the item. To keep it:

```
[Source with binary] ─┬─→ [Edit Fields: transform JSON] ─┐
                      │                                    ├─→ [Merge: by position] ─→ [Email with attachment]
                      └─────────────────────────────────────┘
```

Merge combines the streams, and binary survives. See `references/MERGE_FOR_CONTEXT.md`.

## CDN requirement for chat surfaces

When a workflow generates an image and the user wants it embedded in a chat message (Slack, Discord, Teams, Telegram, embedded webhook chat, etc.):

- **Binary on the item isn't enough.** Chat surfaces don't read `$binary`; they render messages that reference images by URL (or via platform-specific file upload APIs).
- **The image must live somewhere a URL can fetch.** Upload to a CDN or object store first.
- **The user configures this storage.** Not built into n8n.

Common options span object storage (S3, R2, GCS, Azure Blob, Vercel Blob, Supabase Storage) and drive-style services (Dropbox, Google Drive, OneDrive, Box). Ask the user what they use rather than defaulting to S3.

See `references/CDN_REQUIREMENT.md`.

## Data Tables

For Data Tables, see the **`n8n-data-tables-official`** skill. Distinct surface with its own gotchas (default columns, no foreign keys, no JSON column type, manual-mapping UI quirk).

## Reference files

| File | Read when |
|---|---|
| `references/BINARY_BASICS.md` | First time handling binary, or reading/writing the `$binary` slot |
| `references/AGENT_TOOL_BINARY.md` | Agent tool needs a user-uploaded file, or produces a file (the boundary in either direction) |
| `references/MERGE_FOR_CONTEXT.md` | Binary disappears after a JSON transform and needs to re-attach |
| `references/CDN_REQUIREMENT.md` | Showing images in a chat surface or other places that need URL-referenced images |

## Anti-patterns

| Anti-pattern | What goes wrong | Fix |
|---|---|---|
| Trying to read file content from `$json` | Binary isn't in `$json` | Use `$binary` |
| Building an agent tool that returns binary directly | Tool output is JSON-only, so binary doesn't survive | Upload to storage, return key/URL in JSON (see `AGENT_TOOL_BINARY.md`) |
| Trying to pass uploaded chat files into a tool via `fromAi` | `fromAi` doesn't carry binary, so the tool gets nothing | Pre-stage uploads to storage, inject keys in the system prompt, and have the tool download by key |
| Setting `passthroughBinaryImages: true` and assuming tools can now see the file | The flag only affects what the LLM sees, not what tools receive | Still need the upload-and-pass-key pattern for tools |
| Losing binary after a JSON transform | The transform's output item doesn't have binary | Use Merge to combine the JSON output with the binary stream |
| Storing image in n8n binary and expecting a chat surface to display | Chat surfaces need URL-accessible images (or a platform-native file upload), not raw `$binary` | Upload to CDN, embed URL or use the platform's file API |
| Hardcoding binary base64 in a Code node | Massive workflow JSON, slow, leaky | Reference binary via `$binary` properly, or upload to storage and reference by URL |

© n8n-io · Apache-2.0 · n8n-io/skills

Похожие скиллы

Все скиллы по теме «Автоматизация и no-code: n8n, Zapier, Make» →
n8n-binary-and-data czlonkowski Учит агента не терять файлы в n8n: байты лежат в $binary, а не в $json, и через Code-ноду их надо перекладывать явно. Пригодится, когда PDF или картинка исчезает по пути между нодами. CX Codex +1 1 900установок n8n-workflow claude-office-skills Скилл помогает агенту собирать цепочки обработки документов в n8n: от триггера до отправки результата. Пригодится, когда нужно связать PDF, OCR, почту и Slack без ручной работы. CX Codex +1 4 800установок n8n-agents czlonkowski Помогает агенту собирать AI-узлы n8n: выбрать Agent, chain или classifier, подключить память и инструменты, довести структурированный вывод до рабочего состояния. CX Codex +1 1 900установок workflow-automation davila7 Скилл для проектирования воркфлоу с durable execution: шаги переживают сбой сети и продолжают с места остановки. Пригодится, когда платёжный или фоновый процесс нельзя терять. 1 661установок airtable-automation claude-office-skills Помогает агенту проектировать базы Airtable, настраивать представления, формулы и сценарии автоматизации. Пригодится для задач, проектов и связок с n8n. CX Codex +1 6 200установок cloud browser-use Скилл даёт справку по Browser Use Cloud, его API и SDK для браузерной автоматизации. Пригодится для новых облачных интеграций и поддержки v2 или v3. CX Codex +1 3 200установок

Из того же набора14

n8n-credentials-and-security-official Скилл следит, чтобы ключи и токены в воркфлоу n8n шли через систему учётных данных, а не лежали текстом в нодах. CX Codex +1 2 000установок n8n-error-handling-official Скилл для Claude, который заставляет агента настраивать обработку ошибок в n8n: коды ответов по причине, ветки ошибок и аварийные workflow. CX Codex +1 2 000установок n8n-extending-mcp-official Скилл показывает, как завернуть workflow n8n в инструмент, который агент вызывает по имени, если MCP не умеет нужную операцию. CX Codex +1 1 900установок n8n-loops-official Скилл объясняет агенту три модели циклов в n8n: стандартную построчную обработку массивов, переключатель executeOnce и узел Loop Over Items. Помогает избежать лишних дублей и вызовов API. CX Codex +1 1 900установок n8n-subworkflows-official Скилл учит агента выносить повторяющуюся логику n8n в сабворкфлоу с типизированными входами и чистыми контрактами вместо копипасты по воркфлоу. CX Codex +1 1 900установок n8n-expressions-official Скилл задаёт правила для написания выражений n8n в синтаксисе {{...}}. Он заменяет вызовы $json на прямые имена нод и убирает промежуточные узлы Set. CX Codex +1 1 900установок n8n-node-configuration-official Помогает агенту собирать конфиги нод n8n по реальной схеме параметров, а не по памяти. Пригодится, когда воркфлоу ломается на валидации. CX Codex +1 1 900установок n8n-data-tables-official Помогает проектировать схемы, настраивать операции CRUD и хранить состояние сценариев во встроенных Data Tables в n8n. CX Codex +1 1 900установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой