n8n-code-javascript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

JavaScript Code Node

JavaScript Code 节点

Expert guidance for writing JavaScript code in n8n Code nodes.

在n8n Code节点中编写JavaScript代码的专业指南。

Quick Start

快速入门

javascript
// Basic template for Code nodes
const items = $input.all();

// Process data
const processed = items.map(item => ({
  json: {
    ...item.json,
    processed: true,
    timestamp: new Date().toISOString()
  }
}));

return processed;
javascript
// Basic template for Code nodes
const items = $input.all();

// Process data
const processed = items.map(item => ({
  json: {
    ...item.json,
    processed: true,
    timestamp: new Date().toISOString()
  }
}));

return processed;

Essential Rules

核心规则

  1. Choose "Run Once for All Items" mode (recommended for most use cases)
  2. Access data:
    $input.all()
    ,
    $input.first()
    , or
    $input.item
  3. CRITICAL: Must return
    [{json: {...}}]
    format
  4. CRITICAL: Webhook data is under
    $json.body
    (not
    $json
    directly)
  5. Built-ins available: $helpers.httpRequest(), DateTime (Luxon), $jmespath()

  1. 选择「为所有项目运行一次」模式(大多数场景推荐使用)
  2. 访问数据
    $input.all()
    $input.first()
    $input.item
  3. 关键要求:必须返回
    [{json: {...}}]
    格式
  4. 关键要求:Webhook数据位于
    $json.body
    下(不能直接访问
    $json
  5. 内置可用工具:$helpers.httpRequest()、DateTime(Luxon)、$jmespath()

Mode Selection Guide

模式选择指南

The Code node offers two execution modes. Choose based on your use case:
Code节点提供两种执行模式,请根据使用场景选择:

Run Once for All Items (Recommended - Default)

为所有项目运行一次(推荐 - 默认模式)

Use this mode for: 95% of use cases
  • How it works: Code executes once regardless of input count
  • Data access:
    $input.all()
    or
    items
    array
  • Best for: Aggregation, filtering, batch processing, transformations, API calls with all data
  • Performance: Faster for multiple items (single execution)
javascript
// Example: Calculate total from all items
const allItems = $input.all();
const total = allItems.reduce((sum, item) => sum + (item.json.amount || 0), 0);

return [{
  json: {
    total,
    count: allItems.length,
    average: total / allItems.length
  }
}];
When to use:
  • ✅ Comparing items across the dataset
  • ✅ Calculating totals, averages, or statistics
  • ✅ Sorting or ranking items
  • ✅ Deduplication
  • ✅ Building aggregated reports
  • ✅ Combining data from multiple items
适用场景:95%的使用场景
  • 工作原理:无论输入数量多少,代码仅执行一次
  • 数据访问
    $input.all()
    或 items 数组
  • 最佳用途:聚合、过滤、批量处理、数据转换、使用全部数据发起API调用
  • 性能:处理多个项目时速度更快(单次执行)
javascript
// Example: Calculate total from all items
const allItems = $input.all();
const total = allItems.reduce((sum, item) => sum + (item.json.amount || 0), 0);

return [{
  json: {
    total,
    count: allItems.length,
    average: total / allItems.length
  }
}];
适用场景
  • ✅ 对比数据集中的多个项目
  • ✅ 计算总计、平均值或统计数据
  • ✅ 排序或排名项目
  • ✅ 去重
  • ✅ 生成聚合报告
  • ✅ 合并多个项目的数据

Run Once for Each Item

为每个项目运行一次

Use this mode for: Specialized cases only
  • How it works: Code executes separately for each input item
  • Data access:
    $input.item
    or
    $item
  • Best for: Item-specific logic, independent operations, per-item validation
  • Performance: Slower for large datasets (multiple executions)
javascript
// Example: Add processing timestamp to each item
const item = $input.item;

return [{
  json: {
    ...item.json,
    processed: true,
    processedAt: new Date().toISOString()
  }
}];
When to use:
  • ✅ Each item needs independent API call
  • ✅ Per-item validation with different error handling
  • ✅ Item-specific transformations based on item properties
  • ✅ When items must be processed separately for business logic
Decision Shortcut:
  • Need to look at multiple items? → Use "All Items" mode
  • Each item completely independent? → Use "Each Item" mode
  • Not sure? → Use "All Items" mode (you can always loop inside)

适用场景:仅特殊场景使用
  • 工作原理:代码针对每个输入项目单独执行
  • 数据访问
    $input.item
    $item
  • 最佳用途:项目专属逻辑、独立操作、逐个项目验证
  • 性能:处理大型数据集时速度较慢(多次执行)
javascript
// Example: Add processing timestamp to each item
const item = $input.item;

return [{
  json: {
    ...item.json,
    processed: true,
    processedAt: new Date().toISOString()
  }
}];
适用场景
  • ✅ 每个项目需要独立发起API调用
  • ✅ 针对每个项目的验证逻辑需不同的错误处理
  • ✅ 根据项目属性进行项目专属的数据转换
  • ✅ 业务逻辑要求项目必须单独处理
决策捷径
  • 需要查看多个项目? → 使用「所有项目」模式
  • 每个项目完全独立? → 使用「每个项目」模式
  • 不确定? → 使用「所有项目」模式(可在代码内部实现循环)

Data Access Patterns

数据访问模式

Pattern 1: $input.all() - Most Common

模式1:$input.all() - 最常用

Use when: Processing arrays, batch operations, aggregations
javascript
// Get all items from previous node
const allItems = $input.all();

// Filter, map, reduce as needed
const valid = allItems.filter(item => item.json.status === 'active');
const mapped = valid.map(item => ({
  json: {
    id: item.json.id,
    name: item.json.name
  }
}));

return mapped;
适用场景:处理数组、批量操作、聚合
javascript
// Get all items from previous node
const allItems = $input.all();

// Filter, map, reduce as needed
const valid = allItems.filter(item => item.json.status === 'active');
const mapped = valid.map(item => ({
  json: {
    id: item.json.id,
    name: item.json.name
  }
}));

return mapped;

Pattern 2: $input.first() - Very Common

模式2:$input.first() - 非常常用

Use when: Working with single objects, API responses, first-in-first-out
javascript
// Get first item only
const firstItem = $input.first();
const data = firstItem.json;

return [{
  json: {
    result: processData(data),
    processedAt: new Date().toISOString()
  }
}];
适用场景:处理单个对象、API响应、先进先出场景
javascript
// Get first item only
const firstItem = $input.first();
const data = firstItem.json;

return [{
  json: {
    result: processData(data),
    processedAt: new Date().toISOString()
  }
}];

Pattern 3: $input.item - Each Item Mode Only

模式3:$input.item - 仅适用于「每个项目」模式

Use when: In "Run Once for Each Item" mode
javascript
// Current item in loop (Each Item mode only)
const currentItem = $input.item;

return [{
  json: {
    ...currentItem.json,
    itemProcessed: true
  }
}];
适用场景:处于「为每个项目运行一次」模式时
javascript
// Current item in loop (Each Item mode only)
const currentItem = $input.item;

return [{
  json: {
    ...currentItem.json,
    itemProcessed: true
  }
}];

Pattern 4: $node - Reference Other Nodes

模式4:$node - 引用其他节点

Use when: Need data from specific nodes in workflow
javascript
// Get output from specific node
const webhookData = $node["Webhook"].json;
const httpData = $node["HTTP Request"].json;

return [{
  json: {
    combined: {
      webhook: webhookData,
      api: httpData
    }
  }
}];
See: DATA_ACCESS.md for comprehensive guide

适用场景:需要工作流中特定节点的数据
javascript
// Get output from specific node
const webhookData = $node["Webhook"].json;
const httpData = $node["HTTP Request"].json;

return [{
  json: {
    combined: {
      webhook: webhookData,
      api: httpData
    }
  }
}];
参考DATA_ACCESS.md 完整指南

Critical: Webhook Data Structure

关键注意事项:Webhook数据结构

MOST COMMON MISTAKE: Webhook data is nested under
.body
javascript
// ❌ WRONG - Will return undefined
const name = $json.name;
const email = $json.email;

// ✅ CORRECT - Webhook data is under .body
const name = $json.body.name;
const email = $json.body.email;

// Or with $input
const webhookData = $input.first().json.body;
const name = webhookData.name;
Why: Webhook node wraps all request data under
body
property. This includes POST data, query parameters, and JSON payloads.
See: DATA_ACCESS.md for full webhook structure details

最常见错误:Webhook数据嵌套在
.body
javascript
// ❌ WRONG - Will return undefined
const name = $json.name;
const email = $json.email;

// ✅ CORRECT - Webhook data is under .body
const name = $json.body.name;
const email = $json.body.email;

// Or with $input
const webhookData = $input.first().json.body;
const name = webhookData.name;
原因:Webhook节点会将所有请求数据包裹在
body
属性下,包括POST数据、查询参数和JSON负载。
参考DATA_ACCESS.md 完整Webhook结构详情

Return Format Requirements

返回格式要求

CRITICAL RULE: Always return array of objects with
json
property
关键规则:必须返回包含
json
属性的对象数组

Correct Return Formats

正确返回格式

javascript
// ✅ Single result
return [{
  json: {
    field1: value1,
    field2: value2
  }
}];

// ✅ Multiple results
return [
  {json: {id: 1, data: 'first'}},
  {json: {id: 2, data: 'second'}}
];

// ✅ Transformed array
const transformed = $input.all()
  .filter(item => item.json.valid)
  .map(item => ({
    json: {
      id: item.json.id,
      processed: true
    }
  }));
return transformed;

// ✅ Empty result (when no data to return)
return [];

// ✅ Conditional return
if (shouldProcess) {
  return [{json: processedData}];
} else {
  return [];
}
javascript
// ✅ Single result
return [{
  json: {
    field1: value1,
    field2: value2
  }
}];

// ✅ Multiple results
return [
  {json: {id: 1, data: 'first'}},
  {json: {id: 2, data: 'second'}}
];

// ✅ Transformed array
const transformed = $input.all()
  .filter(item => item.json.valid)
  .map(item => ({
    json: {
      id: item.json.id,
      processed: true
    }
  }));
return transformed;

// ✅ Empty result (when no data to return)
return [];

// ✅ Conditional return
if (shouldProcess) {
  return [{json: processedData}];
} else {
  return [];
}

Incorrect Return Formats

错误返回格式

javascript
// ❌ WRONG: Object without array wrapper
return {
  json: {field: value}
};

// ❌ WRONG: Array without json wrapper
return [{field: value}];

// ❌ WRONG: Plain string
return "processed";

// ❌ WRONG: Raw data without mapping
return $input.all();  // Missing .map()

// ❌ WRONG: Incomplete structure
return [{data: value}];  // Should be {json: value}
Why it matters: Next nodes expect array format. Incorrect format causes workflow execution to fail.
See: ERROR_PATTERNS.md #3 for detailed error solutions

javascript
// ❌ WRONG: Object without array wrapper
return {
  json: {field: value}
};

// ❌ WRONG: Array without json wrapper
return [{field: value}];

// ❌ WRONG: Plain string
return "processed";

// ❌ WRONG: Raw data without mapping
return $input.all();  // Missing .map()

// ❌ WRONG: Incomplete structure
return [{data: value}];  // Should be {json: value}
重要性:后续节点需要数组格式,错误格式会导致工作流执行失败。
参考ERROR_PATTERNS.md #3 详细错误解决方案

Common Patterns Overview

常见模式概述

Based on production workflows, here are the most useful patterns:
基于生产环境工作流,以下是最实用的模式:

1. Multi-Source Data Aggregation

1. 多源数据聚合

Combine data from multiple APIs, webhooks, or nodes
javascript
const allItems = $input.all();
const results = [];

for (const item of allItems) {
  const sourceName = item.json.name || 'Unknown';
  // Parse source-specific structure
  if (sourceName === 'API1' && item.json.data) {
    results.push({
      json: {
        title: item.json.data.title,
        source: 'API1'
      }
    });
  }
}

return results;
合并来自多个API、Webhook或节点的数据
javascript
const allItems = $input.all();
const results = [];

for (const item of allItems) {
  const sourceName = item.json.name || 'Unknown';
  // Parse source-specific structure
  if (sourceName === 'API1' && item.json.data) {
    results.push({
      json: {
        title: item.json.data.title,
        source: 'API1'
      }
    });
  }
}

return results;

2. Filtering with Regex

2. 正则表达式过滤

Extract patterns, mentions, or keywords from text
javascript
const pattern = /\b([A-Z]{2,5})\b/g;
const matches = {};

for (const item of $input.all()) {
  const text = item.json.text;
  const found = text.match(pattern);

  if (found) {
    found.forEach(match => {
      matches[match] = (matches[match] || 0) + 1;
    });
  }
}

return [{json: {matches}}];
从文本中提取模式、提及内容或关键词
javascript
const pattern = /\b([A-Z]{2,5})\b/g;
const matches = {};

for (const item of $input.all()) {
  const text = item.json.text;
  const found = text.match(pattern);

  if (found) {
    found.forEach(match => {
      matches[match] = (matches[match] || 0) + 1;
    });
  }
}

return [{json: {matches}}];

3. Data Transformation & Enrichment

3. 数据转换与增强

Map fields, normalize formats, add computed fields
javascript
const items = $input.all();

return items.map(item => {
  const data = item.json;
  const nameParts = data.name.split(' ');

  return {
    json: {
      first_name: nameParts[0],
      last_name: nameParts.slice(1).join(' '),
      email: data.email,
      created_at: new Date().toISOString()
    }
  };
});
映射字段、标准化格式、添加计算字段
javascript
const items = $input.all();

return items.map(item => {
  const data = item.json;
  const nameParts = data.name.split(' ');

  return {
    json: {
      first_name: nameParts[0],
      last_name: nameParts.slice(1).join(' '),
      email: data.email,
      created_at: new Date().toISOString()
    }
  };
});

4. Top N Filtering & Ranking

4. 前N项过滤与排名

Sort and limit results
javascript
const items = $input.all();

const topItems = items
  .sort((a, b) => (b.json.score || 0) - (a.json.score || 0))
  .slice(0, 10);

return topItems.map(item => ({json: item.json}));
排序并限制结果数量
javascript
const items = $input.all();

const topItems = items
  .sort((a, b) => (b.json.score || 0) - (a.json.score || 0))
  .slice(0, 10);

return topItems.map(item => ({json: item.json}));

5. Aggregation & Reporting

5. 聚合与报告

Sum, count, group data
javascript
const items = $input.all();
const total = items.reduce((sum, item) => sum + (item.json.amount || 0), 0);

return [{
  json: {
    total,
    count: items.length,
    average: total / items.length,
    timestamp: new Date().toISOString()
  }
}];
See: COMMON_PATTERNS.md for 10 detailed production patterns

求和、计数、分组数据
javascript
const items = $input.all();
const total = items.reduce((sum, item) => sum + (item.json.amount || 0), 0);

return [{
  json: {
    total,
    count: items.length,
    average: total / items.length,
    timestamp: new Date().toISOString()
  }
}];
参考COMMON_PATTERNS.md 10种经过生产验证的详细模式

Error Prevention - Top 5 Mistakes

错误预防 - 五大常见错误

#1: Empty Code or Missing Return (Most Common)

#1:代码为空或缺少返回语句(最常见)

javascript
// ❌ WRONG: No return statement
const items = $input.all();
// ... processing code ...
// Forgot to return!

// ✅ CORRECT: Always return data
const items = $input.all();
// ... processing ...
return items.map(item => ({json: item.json}));
javascript
// ❌ WRONG: No return statement
const items = $input.all();
// ... processing code ...
// Forgot to return!

// ✅ CORRECT: Always return data
const items = $input.all();
// ... processing ...
return items.map(item => ({json: item.json}));

#2: Expression Syntax Confusion

#2:表达式语法混淆

javascript
// ❌ WRONG: Using n8n expression syntax in code
const value = "{{ $json.field }}";

// ✅ CORRECT: Use JavaScript template literals
const value = `${$json.field}`;

// ✅ CORRECT: Direct access
const value = $input.first().json.field;
javascript
// ❌ WRONG: Using n8n expression syntax in code
const value = "{{ $json.field }}";

// ✅ CORRECT: Use JavaScript template literals
const value = `${$json.field}`;

// ✅ CORRECT: Direct access
const value = $input.first().json.field;

#3: Incorrect Return Wrapper

#3:返回格式错误

javascript
// ❌ WRONG: Returning object instead of array
return {json: {result: 'success'}};

// ✅ CORRECT: Array wrapper required
return [{json: {result: 'success'}}];
javascript
// ❌ WRONG: Returning object instead of array
return {json: {result: 'success'}};

// ✅ CORRECT: Array wrapper required
return [{json: {result: 'success'}}];

#4: Missing Null Checks

#4:缺少空值检查

javascript
// ❌ WRONG: Crashes if field doesn't exist
const value = item.json.user.email;

// ✅ CORRECT: Safe access with optional chaining
const value = item.json?.user?.email || 'no-email@example.com';

// ✅ CORRECT: Guard clause
if (!item.json.user) {
  return [];
}
const value = item.json.user.email;
javascript
// ❌ WRONG: Crashes if field doesn't exist
const value = item.json.user.email;

// ✅ CORRECT: Safe access with optional chaining
const value = item.json?.user?.email || 'no-email@example.com';

// ✅ CORRECT: Guard clause
if (!item.json.user) {
  return [];
}
const value = item.json.user.email;

#5: Webhook Body Nesting

#5:Webhook数据嵌套错误

javascript
// ❌ WRONG: Direct access to webhook data
const email = $json.email;

// ✅ CORRECT: Webhook data under .body
const email = $json.body.email;
See: ERROR_PATTERNS.md for comprehensive error guide

javascript
// ❌ WRONG: Direct access to webhook data
const email = $json.email;

// ✅ CORRECT: Webhook data under .body
const email = $json.body.email;
参考ERROR_PATTERNS.md 完整错误指南

Built-in Functions & Helpers

内置函数与辅助工具

$helpers.httpRequest()

$helpers.httpRequest()

Make HTTP requests from within code:
javascript
const response = await $helpers.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/data',
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json'
  }
});

return [{json: {data: response}}];
在代码内部发起HTTP请求:
javascript
const response = await $helpers.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/data',
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json'
  }
});

return [{json: {data: response}}];

DateTime (Luxon)

DateTime(Luxon)

Date and time operations:
javascript
// Current time
const now = DateTime.now();

// Format dates
const formatted = now.toFormat('yyyy-MM-dd');
const iso = now.toISO();

// Date arithmetic
const tomorrow = now.plus({days: 1});
const lastWeek = now.minus({weeks: 1});

return [{
  json: {
    today: formatted,
    tomorrow: tomorrow.toFormat('yyyy-MM-dd')
  }
}];
日期与时间操作:
javascript
// Current time
const now = DateTime.now();

// Format dates
const formatted = now.toFormat('yyyy-MM-dd');
const iso = now.toISO();

// Date arithmetic
const tomorrow = now.plus({days: 1});
const lastWeek = now.minus({weeks: 1});

return [{
  json: {
    today: formatted,
    tomorrow: tomorrow.toFormat('yyyy-MM-dd')
  }
}];

$jmespath()

$jmespath()

Query JSON structures:
javascript
const data = $input.first().json;

// Filter array
const adults = $jmespath(data, 'users[?age >= `18`]');

// Extract fields
const names = $jmespath(data, 'users[*].name');

return [{json: {adults, names}}];
See: BUILTIN_FUNCTIONS.md for complete reference

查询JSON结构:
javascript
const data = $input.first().json;

// Filter array
const adults = $jmespath(data, 'users[?age >= `18`]');

// Extract fields
const names = $jmespath(data, 'users[*].name');

return [{json: {adults, names}}];
参考BUILTIN_FUNCTIONS.md 完整参考文档

Best Practices

最佳实践

1. Always Validate Input Data

1. 始终验证输入数据

javascript
const items = $input.all();

// Check if data exists
if (!items || items.length === 0) {
  return [];
}

// Validate structure
if (!items[0].json) {
  return [{json: {error: 'Invalid input format'}}];
}

// Continue processing...
javascript
const items = $input.all();

// Check if data exists
if (!items || items.length === 0) {
  return [];
}

// Validate structure
if (!items[0].json) {
  return [{json: {error: 'Invalid input format'}}];
}

// Continue processing...

2. Use Try-Catch for Error Handling

2. 使用Try-Catch进行错误处理

javascript
try {
  const response = await $helpers.httpRequest({
    url: 'https://api.example.com/data'
  });

  return [{json: {success: true, data: response}}];
} catch (error) {
  return [{
    json: {
      success: false,
      error: error.message
    }
  }];
}
javascript
try {
  const response = await $helpers.httpRequest({
    url: 'https://api.example.com/data'
  });

  return [{json: {success: true, data: response}}];
} catch (error) {
  return [{
    json: {
      success: false,
      error: error.message
    }
  }];
}

3. Prefer Array Methods Over Loops

3. 优先使用数组方法而非循环

javascript
// ✅ GOOD: Functional approach
const processed = $input.all()
  .filter(item => item.json.valid)
  .map(item => ({json: {id: item.json.id}}));

// ❌ SLOWER: Manual loop
const processed = [];
for (const item of $input.all()) {
  if (item.json.valid) {
    processed.push({json: {id: item.json.id}});
  }
}
javascript
// ✅ GOOD: Functional approach
const processed = $input.all()
  .filter(item => item.json.valid)
  .map(item => ({json: {id: item.json.id}}));

// ❌ SLOWER: Manual loop
const processed = [];
for (const item of $input.all()) {
  if (item.json.valid) {
    processed.push({json: {id: item.json.id}});
  }
}

4. Filter Early, Process Late

4. 先过滤,后处理

javascript
// ✅ GOOD: Filter first to reduce processing
const processed = $input.all()
  .filter(item => item.json.status === 'active')  // Reduce dataset first
  .map(item => expensiveTransformation(item));  // Then transform

// ❌ WASTEFUL: Transform everything, then filter
const processed = $input.all()
  .map(item => expensiveTransformation(item))  // Wastes CPU
  .filter(item => item.json.status === 'active');
javascript
// ✅ GOOD: Filter first to reduce processing
const processed = $input.all()
  .filter(item => item.json.status === 'active')  // Reduce dataset first
  .map(item => expensiveTransformation(item));  // Then transform

// ❌ WASTEFUL: Transform everything, then filter
const processed = $input.all()
  .map(item => expensiveTransformation(item))  // Wastes CPU
  .filter(item => item.json.status === 'active');

5. Use Descriptive Variable Names

5. 使用具有描述性的变量名

javascript
// ✅ GOOD: Clear intent
const activeUsers = $input.all().filter(item => item.json.active);
const totalRevenue = activeUsers.reduce((sum, user) => sum + user.json.revenue, 0);

// ❌ BAD: Unclear purpose
const a = $input.all().filter(item => item.json.active);
const t = a.reduce((s, u) => s + u.json.revenue, 0);
javascript
// ✅ GOOD: Clear intent
const activeUsers = $input.all().filter(item => item.json.active);
const totalRevenue = activeUsers.reduce((sum, user) => sum + user.json.revenue, 0);

// ❌ BAD: Unclear purpose
const a = $input.all().filter(item => item.json.active);
const t = a.reduce((s, u) => s + u.json.revenue, 0);

6. Debug with console.log()

6. 使用console.log()调试

javascript
// Debug statements appear in browser console
const items = $input.all();
console.log(`Processing ${items.length} items`);

for (const item of items) {
  console.log('Item data:', item.json);
  // Process...
}

return result;

javascript
// Debug statements appear in browser console
const items = $input.all();
console.log(`Processing ${items.length} items`);

for (const item of items) {
  console.log('Item data:', item.json);
  // Process...
}

return result;

When to Use Code Node

何时使用Code节点

Use Code node when:
  • ✅ Complex transformations requiring multiple steps
  • ✅ Custom calculations or business logic
  • ✅ Recursive operations
  • ✅ API response parsing with complex structure
  • ✅ Multi-step conditionals
  • ✅ Data aggregation across items
Consider other nodes when:
  • ❌ Simple field mapping → Use Set node
  • ❌ Basic filtering → Use Filter node
  • ❌ Simple conditionals → Use IF or Switch node
  • ❌ HTTP requests only → Use HTTP Request node
Code node excels at: Complex logic that would require chaining many simple nodes

在以下场景使用Code节点:
  • ✅ 需要多步骤的复杂数据转换
  • ✅ 自定义计算或业务逻辑
  • ✅ 递归操作
  • ✅ 解析结构复杂的API响应
  • ✅ 多步骤条件判断
  • ✅ 跨项目的数据聚合
在以下场景考虑使用其他节点:
  • ❌ 简单字段映射 → 使用 Set 节点
  • ❌ 基础过滤 → 使用 Filter 节点
  • ❌ 简单条件判断 → 使用 IFSwitch 节点
  • ❌ 仅需发起HTTP请求 → 使用 HTTP Request 节点
Code节点的优势:处理需要串联多个简单节点才能实现的复杂逻辑

Integration with Other Skills

与其他技能的集成

Works With:

兼容技能:

n8n Expression Syntax:
  • Expressions use
    {{ }}
    syntax in other nodes
  • Code nodes use JavaScript directly (no
    {{ }}
    )
  • When to use expressions vs code
n8n MCP Tools Expert:
  • How to find Code node:
    search_nodes({query: "code"})
  • Get configuration help:
    get_node_essentials("nodes-base.code")
  • Validate code:
    validate_node_operation()
n8n Node Configuration:
  • Mode selection (All Items vs Each Item)
  • Language selection (JavaScript vs Python)
  • Understanding property dependencies
n8n Workflow Patterns:
  • Code nodes in transformation step
  • Webhook → Code → API pattern
  • Error handling in workflows
n8n Validation Expert:
  • Validate Code node configuration
  • Handle validation errors
  • Auto-fix common issues

n8n表达式语法
  • 其他节点使用
    {{ }}
    语法的表达式
  • Code节点直接使用JavaScript(无需
    {{ }}
  • 了解何时使用表达式 vs 代码
n8n MCP工具专家
  • 如何查找Code节点:
    search_nodes({query: "code"})
  • 获取配置帮助:
    get_node_essentials("nodes-base.code")
  • 验证代码:
    validate_node_operation()
n8n节点配置
  • 模式选择(所有项目 vs 每个项目)
  • 语言选择(JavaScript vs Python)
  • 理解属性依赖关系
n8n工作流模式
  • 数据转换步骤中的Code节点
  • Webhook → Code → API 模式
  • 工作流中的错误处理
n8n验证专家
  • 验证Code节点配置
  • 处理验证错误
  • 自动修复常见问题

Quick Reference Checklist

快速参考检查清单

Before deploying Code nodes, verify:
  • Code is not empty - Must have meaningful logic
  • Return statement exists - Must return array of objects
  • Proper return format - Each item:
    {json: {...}}
  • Data access correct - Using
    $input.all()
    ,
    $input.first()
    , or
    $input.item
  • No n8n expressions - Use JavaScript template literals:
    `${value}`
  • Error handling - Guard clauses for null/undefined inputs
  • Webhook data - Access via
    .body
    if from webhook
  • Mode selection - "All Items" for most cases
  • Performance - Prefer map/filter over manual loops
  • Output consistent - All code paths return same structure

部署Code节点前,请验证:
  • 代码非空 - 必须包含有意义的逻辑
  • 存在返回语句 - 必须返回对象数组
  • 返回格式正确 - 每个项目格式为
    {json: {...}}
  • 数据访问正确 - 使用
    $input.all()
    $input.first()
    $input.item
  • 未使用n8n表达式 - 使用JavaScript模板字符串:
    `${value}`
  • 错误处理 - 为空值/未定义输入添加保护语句
  • Webhook数据 - 若来自Webhook,需通过
    .body
    访问
  • 模式选择正确 - 大多数场景使用「所有项目」模式
  • 性能优化 - 优先使用map/filter而非手动循环
  • 输出格式一致 - 所有代码路径返回相同结构

Additional Resources

额外资源

Related Files

相关文档

  • DATA_ACCESS.md - Comprehensive data access patterns
  • COMMON_PATTERNS.md - 10 production-tested patterns
  • ERROR_PATTERNS.md - Top 5 errors and solutions
  • BUILTIN_FUNCTIONS.md - Complete built-in reference
  • DATA_ACCESS.md - 完整数据访问模式指南
  • COMMON_PATTERNS.md - 10种生产验证模式
  • ERROR_PATTERNS.md - 五大错误及解决方案
  • BUILTIN_FUNCTIONS.md - 完整内置函数参考

n8n Documentation

n8n官方文档


Ready to write JavaScript in n8n Code nodes! Start with simple transformations, use the error patterns guide to avoid common mistakes, and reference the pattern library for production-ready examples.

准备好在n8n Code节点中编写JavaScript了! 从简单的数据转换开始,使用错误模式指南避免常见问题,参考模式库获取生产就绪的示例。