Course/Chapter 4/5. Code & Function Nodes
    beginner
    Chapter 4: n8n Nodes Deep Dive

    5. Code & Function Nodes

    Write custom JavaScript or Python.

    20m Lesson 5 of 6

    When built-in nodes aren't enough, the Code node lets you write custom JavaScript (or Python) to transform data, implement complex logic, or call external libraries.

    Code Node Modes

    • - Run Once for All Items: Process all items together (great for aggregation)
    • - Run Once for Each Item: Process items individually

    Code Examples

    Code Node — Transform Data
    javascript
    // Process all items at once
    const items = $input.all();
    
    const result = items.map(item => {
      const data = item.json;
      return {
        json: {
          fullName: `${data.firstName} ${data.lastName}`,
          email: data.email.toLowerCase(),
          isVIP: data.totalPurchases > 1000,
          joinedDaysAgo: Math.floor(
            (Date.now() - new Date(data.createdAt)) / 86400000
          )
        }
      };
    });
    
    return result;
    Code Node — Aggregate Data
    javascript
    // Summarize order data
    const orders = $input.all().map(i => i.json);
    
    const summary = {
      totalOrders: orders.length,
      totalRevenue: orders.reduce((sum, o) => sum + o.amount, 0),
      avgOrderValue: orders.reduce((sum, o) => sum + o.amount, 0) / orders.length,
      topProduct: Object.entries(
        orders.reduce((acc, o) => {
          acc[o.product] = (acc[o.product] || 0) + 1;
          return acc;
        }, {})
      ).sort((a, b) => b[1] - a[1])[0]?.[0]
    };
    
    return [{ json: summary }];

    Pro Tips

    • 💡Use "Run Once for All Items" when you need to aggregate or compare across items
    • 💡You can require npm packages in self-hosted n8n by setting NODE_FUNCTION_ALLOW_EXTERNAL

    Comprehension Quiz

    Answer 2 of 2 correctly to unlock lesson completion.

    1. What does "Run Once for All Items" mode do?

    2. How can you use external npm packages in the Code node?

    Pass the quiz above to unlock lesson completion