Maker.io main logo

How to Use Variables in Node-RED

2022-09-28 | By Maker.io Staff

Node-RED is a node-based programming tool that lets users construct data-driven IoT applications with minimum effort. As mentioned in a previous article, nodes in Node-RED pass along messages to communicate. However, they can also modify the message contents, add fields, and read data added to a message object by previous nodes. While this approach takes a while to get used to, it’s a solid method for working with data-driven applications. Alternatively, makers can also work with variables in Node-RED, which can be helpful for various other tasks that are more difficult to implement using message-passing. This article looks at how variables function in Node-RED and how to employ them in custom flows.

What Is Node-RED Variables?

While Node-RED lets you write short JavaScript snippets using particular scripting nodes, it is not like other conventional programming languages. Instead of building program logic, like many node-based approaches (such as Scratch), Node-RED focuses on APIs, data, and messages. These messages are one way for nodes to exchange data. However, depending on the variable's scope, you can also use variables to make specific values available to all nodes in a flow and even across flows.

In Node-RED, the scope of a variable describes which parts of a project can read and change a variable's value. A node variable is only visible within the node that defines the variable, for example, a variable used in a short JavaScript snippet. On the other hand, flow variables are accessible from every node within the same flow. Finally, all nodes across all flows can access the value of a variable with global scope, making them a good choice for effortlessly exchanging data between flows.

Working With Variables in Node-RED

Using the change node is one of the easiest ways to create, delete, and update variables in Node-RED. Once triggered, the change node can create and alter flow and global variables. In addition, the change node lets you define custom behavior, for example, increasing an integer value, by employing JSONata expressions.

Consider the following example flow that creates a flow variable, called count, and then sets the variable’s value to zero before displaying the result on the debug monitor. Start by creating an inject node that uses the variable in its message object. I also set the node to inject messages once every second automatically:

 Image of Use Variables in Node-REDCreate three nodes, as shown in the image. Then, double-click the inject node and change its settings as highlighted by the annotations on the image.

Unlike in classic programming languages, you don’t need to worry about the variable not existing because node-RED creates a variable whenever its name first appears in a node. For the sake of demonstration, the change node then sets the counter value to zero, as illustrated by the following image:

 Image of Use Variables in Node-REDThe change node can set, change, and delete variables. This example sets the count flow variable to zero.

Finally, the green debug node shows the result using the debug window of Node-RED:

 Image of Use Variables in Node-REDOnce deployed, the flow should automatically produce an output every second.

Implementing a Simple Counter in Node-RED Using a change node

So far, the flow creates a variable and assigns a value. While this approach is typically enough to extract static values from more complex objects (e.g., response objects returned by an API) it’s not enough to implement a counter, as the value will always be zero. However, as mentioned above, the change node can also dynamically manipulate values using JSONata expressions.

First, change the flow from above, so it looks like in the image below. Then, make sure that the first inject node runs once after 0.1 seconds, and make the second one run after one second with periodic repeat turned on, like before. Then, connect the first inject node to the change node from the first example. Finally, add a new change node and connect the second inject node to the new node before connecting the debug node to the output of the new change node:

Image of Use Variables in Node-RED Rearrange the nodes from before, as shown in this image. Then, add a new change node and name it "increment count".

Next, double-click the new change node and use the following settings to make it increment the counter variable with every input message:

Image of Use Variables in Node-RED Use the new change node to set the message payload and increment the count variable, as shown in this image.

As you can see in the image above, the new change node first sets the message payload to the count flow variable. Make sure to perform this step before altering the variable’s value below, as Node-RED may not use the correct value otherwise. In the second step, the change node then uses a JSONata expression to receive the payload set above. It then increments this value and assigns it to the count variable, thereby incrementing the variable’s value by one with every iteration:

Image of Use Variables in Node-RED The message payload then contains the counter variable’s value that changes with every incoming message.

Reading and Writing Variable Values Using Function Nodes

Finally, you can also create, read, and write variable values in Node-RED using JavaScript function nodes. Start by replacing the “increment count” change node from above with a function node:

Image of Use Variables in Node-RED Use a function node in place of the second change node from before.

Next, double-click the function node and input the following script in the “on message” tab:

Copy Code
var cnt = flow.get("count");

flow.set("count", (cnt + 1));
msg.payload = cnt;

return msg;

The first line of the code snippet reads the count variable’s current value and stores it in a local node variable called cnt. This local variable is only accessible within this single function node. Anyway, the second line increments the local cnt variable by one and then stores the result in the count flow variable. The third line then sets the message payload to cnt before the fourth line returns the message and passes it on to the next node in the chain:

Image of Use Variables in Node-RED The function node produces the same output as before.

Summary

Node-RED focuses on messages to allow nodes to send and receive data. However, variables are an alternative method to store and exchange data between nodes across a single flow or between multiple flows.

Working with variables in Node-RED is not difficult, although it may require some getting used to. This article discussed two ways that allow you to use variables in your Node-RED flows: change nodes and function nodes. change nodes let you create, delete, and update flow and global variables. You can either assign static values or use JSONata to update values dynamically. Function nodes, on the other hand, let you create, read, and update local, flow, and global variables using JavaScript functions.

Recommended Reading

Using NCD Air Quality Sensor with Node-Red

TechForum

Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.

Visit TechForum