Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Leveraging the Code Node in n8n for Custom Workflow Logic

Tech 2

The n8n platform's visual workflow builder has inherent limitations. When pre-built nodes are insuffficient, the Code Node serves as a versatile solution for implemanting custom logic.

Primary use cases for the Code Node include:

  1. Implementing bespoke business logic not achievable through standard nodes.
  2. Processing data in specialized or non-standard formats.
  3. Adding functionality absent from n8n's native node library.
  4. Streamlining workflows by consolidating operations, thereby reducing node count.

A practical guideline is to use visual nodes where possible and employ the Code Node to fill functional gaps, combining both approaches for optimal workflow design.

Code Node Configuration and Execution

Search for code in the node palette to add a Code Node. It supports two programming languages: JavaScript (default and most common) and Python.

The node offers two execution modes:

  • Run Once for All Items (Default): The code executes a single time for the entire batch of input items.
  • Run Once for Each Item: The code executes separately for each individual input item.

The node's operation follows a simple sequence: Receive Input Data → Process Data → Output Data.

Built-in Variables and Functions

n8n's code execution environment provides built-in variables and functions, prefixed with $, which simplify common tasks. Typing $ in the editor triggers autocomplete suggestionss.

For example, outputting today's date is concise with a built-in variable:

console.log($today)

Achieving the same result with native JavaScript requires more code:

function getFormattedCurrentDate(asString = false) {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
  const day = currentDate.getDate().toString().padStart(2, '0');

  if (asString) {
    return `${year}-${month}-${day}`;
  }
  return { year, month, day };
}
console.log(getFormattedCurrentDate(true));

Use console.log() to print debug information to the browser's developer console (F12).

Accessing Data from Preceding Nodes

A common task is processing data passed from upstream nodes. n8n provides methods to easily retrieve this data.

You can reference data from any prior node by its name using the $() selector. For instance, if a preceding HTTP Request node is named FetchUserData, you can access its first output item as follows:

// Access the first item from the node named 'FetchUserData'
const userDataItem = $('FetchUserData').first();
console.log(userDataItem);

The .first() method is used because node output is typically an array of items.

Useful Convenience Methods

n8n includes several helper methods for common operations.

The $ifEmpty() method checks if a value is empty (undefined, null, empty string, array, or object) and returns a default if true.

let result = $ifEmpty(someVariable, 'Default Value');

For finding maximum or minimum values in a dataset, use $max() and $min().

let highestValue = $max([10, 25, 5, 42]); // Returns 42
let lowestValue = $min([10, 25, 5, 42]);  // Returns 5

Outputting Data to Subsequent Nodes

The Code Node can transform and structure data for downstream nodes, effectively replicating the functionality of an Edit Fields node.

Data is passed to the next node using a return statement. The returned value becomes the node's output.

To example, you can fetch data from multiple upstream nodes, process it, and return a new, consolidated structure.

// Example: Process and combine data from two source nodes
const sourceA = $('DataSourceA').first().json;
const sourceB = $('DataSourceB').first().json;

const processedOutput = {
  combinedId: sourceA.id + '_' + sourceB.sequence,
  processedTimestamp: new Date().toISOString(),
  originalData: { a: sourceA, b: sourceB }
};

// This object will be sent to the next node in the workflow
return processedOutput;

You can access data from any ancestor node by name and restructure it entirely before passing it forward.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.