HomeHome AutomationNodeRED for beginners: 6. Function node

NodeRED for beginners: 6. Function node

JavaScript in NodeRED - yes it's coding time!

The Function Node is one of the most useful nodes in NodeRED. It’s a javascript editor which doesn’t do much unless you tell it so.  To use the function node we will have to talk about programming. I know it may sound difficult if you have not coded before, but I will try to keep it simple. It’s not a tutorial to JavaScript, a lot of things will be simply ignored. It’s the essentials to get you started with the function node. If you want to learn more, this tutorial is pretty good.

This tutorial will build on Data Processing and JSON Guide, so I would strongly recommend checking it out before you continue.

NodeRED for beginners: 6. Function node

You can get away without using function nodes for a long time. What can be coded inside of the editor, often can be replicated with other nodes and clever flow design. Sooner or later, you will see that using function nodes can decrease the flow clutter on your screen and make your flow easier to read. For most of the time, you will be using that node to save time and space.

Both nodes produce the same payload

Variables

Setting variables in JS is very easy as the JS doesn’t care about the data type. It’s a 2 stage process. You have to create a variable and assign a value to it. To do this you will use var/let command:

var test
test = "Hello World"; //string Hello World

let test
test = 10;  //integer 10

OR

var test = "Hello World";  //string
let test = "10";           //also string

The variables can contain different data types:

  • string (characters and numbers enclosed in “…”, ‘…’ or `…`)
  • number (integers or floats no “..” needed)
  • boolean (true/false – no “..”; spelling matter )
  • object (JSON type objects start with {…} )
  • null or undefined (empty or not assigned variables)

The difference between let and var is the scope in which the variable is accessible, for the most part, there is very little reason to use let, due to how NodeRED works. Since we are talking about the variables, it’s good to learn how to set the global, local and context variables in NodeRED which can be used later – here is a short rundown (for a long one see Data Processing):

Context (in function node)

context.set('YourVariable', value) = x;   // to store a variable (YourVariable)
var x = context.get('YourVariable'); //to retrieve a variable (YourVariable)

Flow (in the same flow)

flow.set('YourVariable', value);    // to store a variable (YourVariable)
var x = flow.get('YourVariable'); //to retrieve a variable (YourVariable)

Global (across all flows)

global.set('YourVariable', value);   // to store a variable (YourVariable)
var x = global.get('YourVariable'); //to retrieve a variable (YourVariable)

Apart from the Global/Flow/Context assignments, all variable will get destroyed. If you want to keep the values, you have to assign it to a msg object:

var x = "You CAN'T touch this";
msg.payload = x;
return msg;

You can also return other objects, however, other nodes will look for the default msg object and msg.topic and msg.payload passed over.

Another thing worth mentioning are strings that use `…` symbols. These strings can be used with special syntax to enter a variable:

var x = "EXTRA";
msg.payload = `This is a message that has an ${x} value`;
return msg;

Operations

Now that you know how to set values, let’s look into some operations. JavaScript is pretty easy to use – you can perform maths on variables using  +,,*,/**,% symbols. Note that if you use + on a string it will join the parts rather then add the numbers together if one of the values is a string.

var x = "10";
var y = 6;
msg.payload = x + y;   //it will return "106"
return msg;

while on the subject of operation, you may need to change a number to a string and another way around. There are 2 very easy functions that will take care of this for you:

ToString

var x = msg.payload          //message is 23
var stringValue = String(x);
msg.payload = stringValue;   //returns message "23"
return msg;

ToNumber

var x = msg.payload //message is "5"
var numberValue = Number(x);
msg.payload = numberValue; //returns message 5
return msg;

This is especially useful if you are getting a stream of data (from a sensor) and you need to process it accordingly. Thankfully the Dashboard already does it for you if you want to create graphs and charts.

Multiple Outputs

Some nodes can return the message to more outputs (see the outputs number below the editor window). This is handy when you have conditional statements. I’ll show you how to do send the messages first before jumping into the conditional statements:

var msg1 = { payload:"Message to the topoutput" };
var msg2 = { payload:"Message to the bottom output" };
return [ msg1, msg2];

If you have seen the JSON tutorial you will see that the function node returns an array is multiple outputs are added.  I wrote more about handling multiple payloads specifically in this article – it’s worth reading.

Comparations

Why have multiple outputs if you cannot send the data this way. Sometimes it’s easier to assign and process information with a function node than the switch node. To use it you have to define statements or switch statements for more precise conditions (yes you have a switch node just for that too!)

if (msg.payload === "PAYLOAD") {
msg.payload = "It was a ok for the 1st statement";
return [msg, null];
} else {
msg.payload = "It's worng";
return [null, msg];
}

If the message is “PAYLOAD” the 1st output is used, otherwise, it’s the second one. I mentioned that the messages returned by the function could be stored as arrays, and here I’m defining which element of the array I refer to:

return [msg, null, null]; // 1st output
return [null, msg, null]; // 2st output
return [null, null, msg]; // 3st output

The same syntax is used if <, >, =>,<=, != are used. But if you need more specific cases, the switch statement could be used instead:

switch (msg.payload) {
case "one":
  msg.payload = 'option one';
  return [msg,null,null,null];

case "two":
  msg.payload = 'option two';
  return [null,msg,null,null];

case "three":
  msg.payload = 'option three';
  return [null,null,msg,null];

default:
  msg.payload = 'other values';
  return [null,null,null,msg];
}

Other functions

Functions are created usually to perform a single task.  The function node is a function itself and it will follow whatever code you have inside it. That doesn’t mean you can’t create functions inside it. You can use JavaScript functions to change and process the information before composing your final message object.

To create the function type:

function calculateSum(x, y){
   var one = Number(x);  //convert to a number
   var two = Number(y);  //convert to a number
   var result = one + two;
return result;
}

msg.payload = calculateSum(msg.payload,msg.topic);
return msg

In this function will take the values from msg.topic and msg.payload and calculates the sum. Before the sum is calculated I have to make sure that both values are numbers, not strings.

Then I can simply set the result as the payload – using the function and the parameters required.

Conclusion

This guide and the proper JavaScript tutorial should get you started. The function node can be a really good timesaver to your flows, and it’s good to know basic concepts. In the next, and the last part I will list some Tips and Tricks that you could use with NodeRED to make your life better.

PayPal

Nothing says "Thank you" better than keeping my coffee jar topped up!

Patreon

Support me on Patreon and get an early access to tutorial files and videos.

image/svg+xml

Bitcoin (BTC)

Use this QR to keep me caffeinated with BTC: 1FwFqqh71mUTENcRe9q4s9AWFgoc8BA9ZU

Smart Ideas with

Automate your space in with these ecosystems and integrate it with other automation services

client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image

Learn NodeRED

NodeRED for beginners: 1. Why do you need a NodeRED server?

0
To server or not to server? That's a very silly question!

Best Automation Projects

Tuya SDK for beginners: Intro to Tuya Cloud API

0
Working with Tuya Cloud API. A guide to Cloud automation for beginners, get started with REST!

NEST your old thermostat under $5

0
Nest-ing up your older thermostat under $5

Sonoff Zigbee Bridge – review

0
Sonoff line up will soon include Sonoff Zigbee Bridge and more Zigbee sensors - here is the first look

DIY Smart Washing Machine – for about 15 bucks!

0
Learn how to add washing machine notifications to your Google Home on the cheap

Nora – Google Assistant in NodeRED

0
Integrate Google Assistant with NodeRED thanks to Nora - NodeRED home automation

Smart Home

Multi-lights for your ceiling from Aqara

0
This is the biggest light I held in my hands so far. It's ZigBee and it comes from Aqara - meet Aqara Ceiling Light T1M

Almost the fastest PIR sensor you can buy

0
ITEAD introduced a new ZigBee sensor - Sonoff PIR (SNZB-03P) which is also the fastest PIR sensor in their line up. Is it good? Read more!

Smart Panel automation by Tuya

0
I'm checking out two smart panels by Tuya. Both run Linux systems, fit inside the wall switch cavity and offer a range of automation options

Adding Matter to Sonoff BasicR4

0
Sonoff goes back to basics with Sonoff BasciR4 - a new and improved basic smart relay - and I'm about to add Matter to it (and Tasmota)

Sonoff Presence Sensor (SNZB-06P) is not what you think

0
This mm wave radar sensor combines cool tech and ZigBee 3.0, but it's not what you think it is. Closer look at Sonoff Presence Sensor