Understanding The Node-Red Message Object

node-red-icon1A node red flow consists of a series on interconnected nodes.(wired nodes).

All nodes must have an input and can have 0 or multiple outputs.

Nodes exchange data using the msg object.



Each node receives the message object from the previous node, and then can pass this message object onto the next node in the flow.

The Msg Object

The message object has several properties depending where it originated.

A msg object that originates from an MQTT input has :

  • payload
  • topic
  • qos
  • _msgid
  • retain

You can see the message properties by sending the msg to the debug node.

node-red-debug-node

By default the debug node will display the msg.payload property but you can edit the node to display all message properties.

node-red-debug-node-edit

This is what you see:

node-red-view-properties

Modifying the msg Object

Any node can read or modify the properties of the msg object, and they can also extend the message object.

Node-red provides various nodes that can change the messages object without you have to write any JavaScript code.

The main ones are change,split,join,switch.

You can find out more of what they do by dragging them onto the flow and then viewing the info tab.

node-red-node-info

See the documentation for more details

Using The Function Node with The Msg Object

You can also modify the msg object using the function node. However to do this you will need to write Javascript code.

When you create a new function node and go to edit then you will see a single line of code that returns the msg object and a blank line above were you start to enter your code.

node-red-function-edit

The msg object is passed into this function by the proceeding node which you don’t see ,and the return at the end passes the msg object onto the next node in the flow.

Even if you don’t modify then msg object then you need the return to pass on the msg object to the next node.

Creating a New Message Object

Inside a function you can create a new msg object using:

var newMsg = { payload: msg.payload,topic:msg.topic };
return newMsg;

However the msg will loose properties of the original message object and may break some flows.

Resources:

Related Tutorials:

Please rate? And use Comments to let me know more
[Total: 2    Average: 3/5]

Leave a Reply

Your email address will not be published. Required fields are marked *