How to Declare Global Variable in Node Red
In this post i will step through 2 Different method on how to Declare a Global Variable in Node Red.
Prior to that , you will need to create 2 Flows to Test out the Global Variable Later
Click the “+” Icon on your right to Create 2 Flow , and provide names to both
In My Case I name it Flow 1 and Flow 2
Method 1
For Method 1 I will use Change node to Set / declare the global Variable
Step 1
In Flow 1 , Drag out and inject Node and Configure as Below
Pass a String Value ” This is A Global String 1 ” to the msg.payload
Step 2
In Flow 1 .Drag Out a Change Node and Configure as below . The Configuration shows that it will pass the data from msg.payload to firstGlobalString
After this Step , you will be able to use “firstGlobalString” Variable in All Flows reside in Node Red
Step 3
Connect the Nodes together.
Now you have completed the node where when trigger it will inject ” This is A Global String 1 ” to the msg.payload. The Change Node will read the msg.payload Value
and Pass the Value into the global Variable “firstGlobalString”
Step 4
Retrieve the global Variable “firstGlobalString” Value
In Flow 2 ,Drag out the inject Node and Configure as below .
The Inject Node will pass the “firstGlobalString “global Variable value into msg.payload
Step 5
In Flow 2 Drag Out a Debug Node , and configure as Below
Step 6
Joint the Nodes, trigger both inject node at Flow 2 and Observe the results
Results
Method 2
For Method 2 I will use Function node to Set / declare the Global Variable
Step 1
In Flow 1 Drag out and inject Node and Configure as Below
Pass a String Value ” This is A Global String 2 ” to the msg.payload
Step 2
In Flow 1 Drag Out a Function Node and Configure as below . The Configuration shows that it will pass the data from msg.payload to global.secondGlobalString
After this Step , you will be able to use “secondGlobalString” global variable for all flow in Node Red
Copy and paste the code below and paste it into the Text Area inside the “On Message ” Tab
Code as below
Step 3
In Flow 1 ,Connect the Nodes together.
Now you have completed the node where when trigger it will inject ” This is A Global String 2 ” to the msg.payload. The Function Node will read the msg.payload Value
and Past the Value into the global Variable “secondGlobalString”
Step 4
In Flow 2 , Retrieve the global Variable “secondString” Value
Drag out the inject Node and Configure as below .
The Inject Node will pass the “secondGlobalString “global Variable value into msg.payload
Step 5
In Flow 2 Drag Out a Debug Node , and configure as Below
Step 6
In Flow 2 Joint the Nodes, trigger both inject node and Observe the results
Results
check out How to Create Flow Variable in Node red
Leave a Reply