Understanding How to Use Node-RED Functions

Navigate to:

In the realm of industrial internet of things (IIoT), automation, and integration, complexities often arise. Sometimes you’re met with data that doesn’t fit the mold or processes that demand customization beyond what’s readily available.

Luckily, when using Node-RED, you get a Node-RED function node that allows you to write custom JavaScript code. The function node enables you to tackle complex data transformations, execute personalized logic, and seamlessly integrate disparate components within your flows.

This post will define Node-RED functions and provide an example of how to use them in your flow. In addition, you’ll get a list of ways you can use Node-RED functions.

What Is Node-RED?

Node-RED is an open-source, flow-based, visual programming tool for wiring hardware devices, APIs, and online services. It provides a browser-based interface that allows you to create flows using nodes. You’ll then connect nodes representing various tasks or components using visual links.

We use Node-RED mostly in the IoT and home automation domains. It simplifies integrating different devices and services by providing a drag-and-drop interface for creating automation logic, data-processing pipelines, and communication between various systems.

node that follows you

What Is a Function in Node-RED?

In Node-RED, a function is a node that allows you to write custom JavaScript code to process and manipulate message data within a flow. You can use the function node when the built-in nodes don’t provide the specific functionality you need or when you want to perform custom data transformation or logic.

Nodes pass message data as a JavaScript object msg, and you access the message’s body using the property msg.payload. The function node should return a message or multiple message objects. However, the function can return nothing if you want to stop the flow.

How Do You Create a Node-RED Function?

Before creating a Node-RED function, ensure you’ve installed and have a Node-RED instance running in your web browser. Connect to your local instance here.

On the left side of the editor, you’ll find a list of nodes grouped by different categories.

Under the function category, you’ll see a function node, which you’ll click and drag to the canvas flow. This is where you’ll customize your flow.

To customize the function, double-click on the function node to open the configuration window.

create Node-RED function

You can adjust the name of your function under the Name field. The name is a descriptive label displayed on the workspace. It’s good practice to label the nodes according to their actions.

Below the name field, there are different tabs that you’ll use to configure and write your JavaScript logic depending on the context.

If you have any logic you want to run at the start of the node, you’ll use the On Start tab to write the relevant JavaScript code. That code will only run once. The On Stop tab is where you’ll write code that should only run when stopping or redeploying the node.

Now, the On Message tab is where the bulk of your logic resides.

Simple Function Example

To see the function node in action, we’ll create a flow that injects a temperature value in Fahrenheit and then have the function convert it to Celsius.

Drag three nodes to the workspace. Start with the inject node. Double-click the node to configure its properties by giving it a descriptive name, and change the msg.payload to a number and give it a value.

Next, add a function node. Double-click the node to open the editor. Give the function node a descriptive name and add the following logic to convert the injected temperature value. This is an example of a synchronous function, as the lines of code will execute sequentially.

// Get the input temperature in Fahrenheit from msg.payload
var fahrenheit = msg.payload;

// Convert Fahrenheit to Celsius
var celsius = (fahrenheit - 32) * (5 / 9);

// Store the result in msg.payload
msg.payload = celsius;

// Return the modified message
return msg;

Finally, add a debug node to display the message payload on the debug sidebar. You can also configure it to output the message payload in your Node-RED instance’s terminal.

Below is the flow output when you inject a temperature of 79 degrees Fahrenheit.

flow output when you inject a temperature of 79 degrees Fahrenheit

Using Async Functions in Node-RED

Asynchronous tasks are operations that don’t finish right away but return their results later after they are called. Some examples include making API calls, reading files, or interacting with databases.

In scenarios where functions require such asynchronous tasks before proceeding, don’t return the message object. Instead, the function must employ the node.send() method to transmit the intended message(s). This method accepts a similar set of parameters to those the function returns.

The function node actively clones every message object you pass to node.send, preventing unintended alterations of message objects that might be reused within the function.

You should note that when a function node engages in asynchronous work involving a message, the runtime won’t inherently discern when the message processing concludes. As such, the function node should proactively invoke node.done(). Invoking node.done allows your runtime to trace messages as they traverse the system accurately.

Resolving any pending requests or closing active connections on each flow redeployment is good practice when using asynchronous callback code within your functions. You can write cleanup logic in the On Stop tab that’ll run during the node’s shutdown.

Alternatively, you may incorporate a close event handler in your function like so:

node.on('close', function() {

    // Implement any necessary tidy-up for asynchronous code here, such as shutting down connections.
});

How Do You Use Functions in Node-RED?

The Node-RED function is versatile, and you can use it for a wide range of tasks within your flow-based automation and integration projects. Some common use cases for Node-RED functions include:

  • Data transformation—This could include converting timestamps, extracting specific fields, or reformatting data for compatibility with other systems.

  • Data filtering and validation—You can use functions to filter out irrelevant data. You can also validate incoming data against specific criteria before allowing it to proceed through the flow.

  • Conditional logic—Functions can implement conditional logic if you need to make decisions based on incoming data. For example, you might route data differently depending on certain conditions or trigger specific actions based on certain values.

  • Mathematical and statistical operations—Functions can perform mathematical calculations or statistical operations on data. This is useful for tasks like aggregating data, calculating averages, determining maximum or minimum values, and more.

  • Text processing—Functions can manipulate text data. You can search for patterns, replace text, truncate strings, capitalize words, and perform other text-related tasks.

  • Date and time manipulation—Functions can help you manipulate and format dates and times as needed if your flow deals with timestamps or date-related data.

  • Error handling—You can implement error-handling mechanisms in functions. For instance, if an error occurs in one part of the flow, you might want to modify the error message or format before passing it to the next node.

  • Dynamic content—You can generate dynamic content in functions, such as constructing dynamic URLs, generating personalized messages, or building dynamic queries.

  • Custom logic—Sometimes your flow might require very specific logic that can’t be achieved using existing nodes. Functions allow you to implement this custom logic.

  • Multi-step processing—In some cases, you might need to perform a series of steps on the incoming data. Functions can facilitate multi-step processing within a single node, reducing the complexity of the flow.

Why Use Functions?

Whether you’re monitoring IoT devices, tracking sensor readings, or analyzing performance metrics, Node-RED functions empower you to transcend the boundaries of pre-built solutions. The function node allows you to infuse your flows with custom logic, data mastery, and creativity.

As you embrace the transformative power of Node-RED functions, consider elevating your data persistence to the next level with InfluxDB. With InfluxDB, you’re not just storing time series data, you’re unlocking the door to a deeper understanding of temporal trends and patterns.

Additional resources

This post was written by Mercy Kibet. Mercy is a full-stack developer with a knack for learning and writing about new and intriguing tech stacks.