How to define Global Functions (and "libraries") in Nodered

GLOBAL FUNCTIONS

Creating global functions in Node-RED can be very useful for reusing code across different flows. Here’s a step-by-step guide on how to create and use global functions:

1. Setting a Global Function

To set a global function, you usually do this in a function node. This function will then be available in any other function node in your Node-RED environment.

Example:

Let’s create a simple global function that multiplies a number by 2.

  1. Add a function node to your flow.
  2. Edit the function node and add the following code:
// Define the function
function multiplyByTwo(x) {
    return x * 2;
}

// Set the function globally
global.set("multiplyByTwo", multiplyByTwo);

// Pass on the msg object to the next node (optional)
return msg;
  1. Deploy the flow.

WARNING: THE FUNCTION NODE CONTAINING THE GLOBAL FUNCTION DEFINITION MUST BE DEPLOYD BEFORE THE FIRST USAGE FROM AN EXTERNAL NODE . YOU CAN USE AN INJECT NODE CONNECTED TO THE DEFINITION FUNCTION NODE.

This code defines a function multiplyByTwo and sets it as a global function using global.set.

2. Using the Global Function

To use this function in another node:

  1. Add another function node where you want to use the global function.
  2. Edit the function node and use the global function. For example:
// Get the global function
var multiplyByTwo = global.get("multiplyByTwo");

// Use the function
msg.payload = multiplyByTwo(msg.payload);

// Return the msg object
return msg;
  1. Connect this node to the rest of your flow as needed.
  2. Deploy the flow.

This code retrieves the global function with global.get and then applies it to the msg.payload.

Tips

  • Modularity: Keep your global functions simple and focused on a single task.
  • Naming Conventions: Use clear and descriptive names for your global functions to avoid confusion.
  • Error Handling: Consider adding error handling within your global functions for robustness.

Using global functions like this helps keep your Node-RED flows more organized and avoids the repetition of code.

GLOBAL FUNCTIONS VS SUBFLOWS

Global Functions

  1. Definition: A global function is a JavaScript function defined in a Node-RED function node and made available to all other function nodes via the global context.
  2. Use Case: Best for reusable code logic, especially small utility functions that perform specific tasks (e.g., data transformation, calculations).
  3. Advantages:
  • Simplicity: Ideal for small, simple tasks.
  • Portability: Can be used across different flows and instances.
  • Flexibility: Being JavaScript, it offers the full power of a programming language.
  1. Disadvantages:
  • Complexity: Not suitable for complex tasks involving multiple steps or nodes.
  • Dependency: The function must be defined before it can be used elsewhere in the flow.
  1. Example: A global function to format a date or calculate a value.

Subflows

  1. Definition: A subflow in Node-RED is a collection of nodes that are grouped together to create a reusable flow. It can be instantiated multiple times within a project.
  2. Use Case: Ideal for complex tasks that involve multiple steps or a series of nodes, like processing a particular type of input data or interacting with specific APIs.
  3. Advantages:
  • Modularity: Encapsulates a sequence of operations into a single, reusable node.
  • Ease of Use: Drag and drop the subflow into your flow, just like any other node.
  • Scalability: Better for complex tasks that require multiple nodes.
  1. Disadvantages:
  • Overhead: More overhead than a simple function for small tasks.
  • Limited Flexibility: You’re limited to the capabilities of the nodes within Node-RED (though this can be extensive).
  1. Example: A subflow for processing incoming sensor data, including parsing, error checking, and logging.

Summary

  • Global Functions are best for simple, repeatable code tasks that can be encapsulated in a JavaScript function.
  • Subflows are more suitable for complex tasks that require multiple nodes and steps.

In practice, a well-organized Node-RED project might use both methods: global functions for utility tasks and subflows for complex processes. The choice depends on the specific requirements of the task at hand and the complexity involved.

3 Likes

HOW TO CREATE A “LIBRARY” IN NODERED

Step 1: Define Your Functions in a Dictionary

  1. Start with a function node: This will be where you define your library.
  2. Create a dictionary of functions: In this node, define a JavaScript object (dictionary) where each property is a function.

Example Code:

// Creating a dictionary of functions
var myLibrary = {
    add: function(a, b) {
        return a + b;
    },
    multiply: function(a, b) {
        return a * b;
    },
    // More functions can be added here
};

// Set this dictionary in the global context
global.set("myLibrary", myLibrary);

// Pass on the msg object (optional)
return msg;

In this example, myLibrary is an object with two functions: add and multiply.

Step 2: Use the Global Function Library in Other Nodes

  1. Retrieve the library: In any other function node where you need to use these functions, you first retrieve the entire library from the global context.
  2. Access the required function: Then you can call any function from this library.

Example Code:

// Retrieve the library from global context
var myLibrary = global.get("myLibrary");

// Use a function from the library
msg.payload = myLibrary.add(5, 3);

// Return the msg object
return msg;

In this example, the add function from myLibrary is used to add 5 and 3.

4 Likes