"Function tried to send a message of type string" error coming

Hello to all,
I am new to the Node Red and trying to code a logic. I am having four Inject buttons and from each button i input one numerical value. These values are fed to the function command which will further generate a payload message of specific color mentioned against the numerical values. Finally i am displaying that color over a indicator made using Template + msg.color command.

Now the only issue here is that i am constantly getting an error message "Function tried to send a message of type string" and my code is not working.

Please help me to resolve this issue, that would be a great support of yours to me !!!

My function code is
var topic = msg.payload;
if(topic == 0)
{
var color = "lime";
color = color.toString();
msg.color = color;
}
if(topic == 1)
{
var color = "red";
color = color.toString();
msg.color = color;
}
if(topic == 2)
{
var color = "orange";
color = color.toString();
msg.color = color;
}
if(topic == 3)
{
var color = "grey";
color = color.toString();
msg.color = color;
}
return[msg.color];

All function nodes must return messages (that is javascript objects) not simple variables. So you need to use
return msg

Hi, a few pointers...

  1. Always put three back ticks ``` on a line above and below your code. Makes it easier to read and in some cases, prevents the forum doing screwy things to your code.
  2. This could be easily achieved with standard nodes like the switch and change nodes. You would do yourself a great favour to give it a go.
  3. Your code is a bit odd and overly verbose. Below is somewhat simplified.
var topic = msg.payload;
if(topic == 0){
  msg.color = "lime";
} else if(topic == 1){
  msg.color = "red";
} else if(topic == 2){
  msg.color = "orange";
} else if(topic == 3) { 
  msg.color = "grey";
} 
return msg;
  1. You might also want to set msg.color to something default incase payload isn't 0~3



One for you to come back to as you get used to programming...

if(msg.payload >= 0 && msg.payload <= 3){
  msg.color = ["lime","red","orange","grey"][msg.payload];
}
return msg;

@Steve-Mcl The code works !!! A Heartiest Thanks to you ......
Please tell me why my return[msg.color] command was wrong.
Also how msg.color = ["lime","red","orange","grey"][msg.payload]; will provide an output against my defined input.

Again a big thanks to you

@Colin Thank you so much !!!

I'm guessing the msg.color = ["lime","red","orange","grey"]part defines msg.color as an array and then the [msg.payload] addresses that array with the 0-3 variable you injected. It's a nice neat way to do it and I really appreciate @Steve-Mcl for showing it.

(Almost) correct :slight_smile:

msg.color never gets assigned the array, only the element prescribed by msg.payload

TBH, it was a solution to a question but not necessarily the best way. Using class names and CSS would be far better solution.

1 Like