First, connect an inject node, two function nodes and two debug nodes like this:
Figure 6.13 Wire up functions for a context example
Let’s edit the first function node and add this code. Set the global element of the context object to have a new element, “hello”, which is an anonymous function that returns the string “Hello There”. Then set the message payload of this function to the return value of this global function. This will print out “Hello There”.
Figure 6.14 Define an anonymous function as a new context element
Now edit the second function node by setting up the message payload of this second function to concatenate the output of the ‘hello’ element (anonymous function) in the global element of the context object with the word “World”:
Figure 6.15 Use the anonymous function defined in another function node
Pressing the button on the inject node shows the output of each of the function nodes:
Figure 6.16 Output of context function sharing example
Despite being very simple, this example shows how easy is to use the context element to set not only variables that contain data, but also functions that can be shared and accessed by several functions in your canvas.
Two important aspects to consider are: firstly, the function setting the global element of the context object must come BEFORE any other function wishing to use that variable or function in the flow. Secondly, in the current version of Node-RED (1.11.0), the context object remains in memory after re-deployment until the Node-RED instance is rebooted. So even after deleting the function nodes that set an elements in the global element, these elements will still be accessible until set to null.
BACK to main Lecture 6