Node-RED: Lecture 3 – Example 3.3 Using a change node to change or manipulate a message payload

Another useful node is the change node, which will allow you to change a message payload or add new properties. You can use this node to affect the properties in a message, either by changing existing ones, deleting them or adding new properties.

In this example, you’ll continue with your MQTT theme and see how, now that you have successfully ‘switched’ the message flow based on the incoming MQTT message, you can add a new message property msg.payload.note.

If you aren’t following these examples sequentially, you may want to review Example 3.1 to see how to setup a free MQTT service and configure the incoming MQTT node used in these examples.

First, let’s drag and drop a change node and connect it to the second output of the switch node (Fig 3.7). As you will remember, this is the output that fires when msg.payload.analyze is set to false.

Figure 3.7 Adding in a change node to set a new message property.

 

Now configure it to set the property msg.payload.note to “this is not being analyzed” as shown in Fig 3.8.

 

Figure 3.8 Using a change node to add a new message property

 

When you receive a message that the switch node sends on the 2nd output, it will be modified to contain a “note” element with the string “this is not being analyzed”. If you deploy and test the flow by sending the MQTT message from HiveMQ, you’ll see the output as shown in Fig 3.9.

 

Figure 3.9 The result of switching and then changing the message

 

You can find the node-red description of this flow at:

https://raw.githubusercontent.com/SenseTecnic/nrguideflows/master/lesson3/3-3_changenode.json

 

Back to Lecture 3

                                   PREVIOUS example                        NEXT example

 


© Lea, Blackstock, Calderon

This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

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.