Node-RED: Lecture 6 – Example 6.4 Using the context element to share a function and make it accessible to all functions in the canvas

This example shows how to use the context object and its global element to share data across function nodes. The example above used this to store a numerical value. However, one of the great things about JavaScript is that you can assign functions to objects. This allows you to share methods across your canvas without the need to redefine them in each consecutively used function node. The contrived example below simplifies this process for better understanding.

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

PREVIOUS example           NEXT Example

Author: Rodger Lea

Currently CEO of Internet of Things startup, Sense Tecnic, Dr. Lea has over 25 years experience spanning academic, large corporations and startups. For the last 10 years, he has started or helped start 4 new companies while managing an active research program (University of British Columbia, Canada and Lancaster University, UK) into distributed and ubiquitous computing, the IoT and Smart Cities.