Date:

Share:

How to Declare Global Variable in Node Red – CreatifWerks

Related Articles

In this post I will go through 2 different methods of how to declare a global variable in red junction.

Before that, you will need to create 2 flows to check the global variable later

Click the “+” icon on your right to create 2 flows, and provide names for both

In my case I call it flow 1 and flow 2

For method 1 I will use the Change node to set/declare the global variable

Level 1

In flow 1, drag out and drop a node and configure as below

Pass a string value “This is a global string 1” to msg.payload

level2

In flow 1. Drag out a change node and set as below. The configuration shows that it will pass the data from msg.payload to firstGlobalString

After this step, you can use the “firstGlobalString” variable in all flows residing in Node Red

Step 3

Connect the nodes together.

You have now completed the node where when the trigger fires it will inject “This is A Global String 1” to msg.payload. The change node will read the msg.payload value

and pass the value to the global variable “firstGlobalString”

Step 4

Retrieve the global value of the “firstGlobalString” variable.

In flow 2, drag out the injection node and set as below.

The Inject Node will pass the global variable value “firstGlobalString” into msg.payload

Step 5

In flow 2 drag out a debug node, and set as down

Step 6

Connect the nodes, run both injection node in flow 2 and watch the results

results

For method 2 I will use the Function node to define / declare the global variable

Level 1

In flow 1 drag out and drop the node and set as below

Pass a string value “This is A Global String 2” to msg.payload

level2

In flow 1 drag out a function node and set the configuration below. The configuration shows that it will pass the data from msg.payload to global.secondGlobalString

After this step, you can use the global variable “secondGlobalString” for all flow in Node Red

Copy and paste the code below and paste it into the text area inside the “In Message” tab.

Code as below

// Declare a global string

global.set(‘secondGlobalString’, msg.payload)

return message;

Step 3

In flow 1, join the nodes together.

You have now completed the node where when the trigger it will inject “This is A Global String 2” to msg.payload. The function node will read the msg.payload value

and pass the value to the global variable “secondGlobalString”

Step 4

In Flow 2, retrieve the “secondString” value of the global variable

Drag out the injection node and set as below.

The Inject Node will pass the value of the global variable “secondGlobalString” to msg.payload

Step 5

In flow 2 drag out a debug node, and set as down

Step 6

In Flow 2 Joint the Nodes, run both the injection node and view the results

results

Check out how to create a flow variable in Node Red

Source

Popular Articles