Friday, July 27, 2018

Understanding Node-red basic nodes with examples

This post is about the basics of core nodes in nodered tutorials

Inject Node

Inject node is an input node used to initialize aflow. You can initialize the flow either manually or automatically using configured time interval. Message object in injects node has payload and topic. By default, the payload is a current timestamp.

Debug node

Debug node is output node used to show messages to debug console This will be very useful during development of flow. usually, the data received from other nodes are input to this debug node
This always displays msg object with payload to debug console

Function Node 

Function node is one of core node of node red palette
You can write javascript code in this node. the message object is an input to this node. the output is the message object.

Function node is dragged to flow editor. Available properties are the name of the node, and code editor where you can write javascript code. Msg object is aviablle and accessed to javascript  Msg.payload is the content of the message.
The function always returns msg object or null. null means no message received
Function node tutorials examples

Function node example printing timestamp

As you see below the screenshot, flow is Inject Node --> Function Node --> Debug Node.
Inject node initiates with an interval of 1 second which sends the request to the Function node. Function node return msg object to debug node to log msg payload to debug console 
function node example

Asynchronous Function 

Sometimes we need to write javascript asynchronous code in function node.
Use node.send(msg) to send the asynchronous request. Normally Function node basically sends the msgs once the request comes. When asynchronous used, It will not send the request immediately until asynchronous is completed
 FunctionAsync(msg, function(output){
Logging ERRORS/warnings
you are writing javascript, if an error occurred, you need to log the error. For that Node object has several methods. console.log will not work as expected, so you have to use node object methods

Node.war("Warning information")
Node.error("ERROR information")
Node.log("Warning information")
Save data to the context 
store during code execution You need to store data in context. Context is kind of global way of storing and sharing data across different nodes.
Context has three scopes
Node scope -  is limited to a specific node.
Flow scope - is accessible to all nodes on the same flow context
Global scope -  is data store in this is accessible to all nodes across all flows