Tried to send a message of type string (function node)

Hello, I am writing the following function, when the message enters the node, the debug reports the following error, someone can help me correct it.

"Error": "Function tried to send a message of type string"

The function :

var status = msg.payload;
var id = global.get ("serial");
var off = 0;
var msg1 = "" + id + "" + "f00" + "" + off + "";
var msg2 = "" + id + "" + "f01" + "" + off + "";
var msg3 = "" + id + "" + "f02" + "" + off + "";


if (state == true) {
    return [msg1, msg2, msg3];
}

The idea is each of those messages comes out through an output of the node, and I already have the node configured with 3 outputs.

All Node-RED messages are an object, so you must always return a msg object from a function node.

What you most likely want to do is return a msg object with msg.payload set to be a string.

var status = msg.payload;
var id = global.get ("serial");
var off = 0;
var msg1 = { payload: "" + id + "" + "f00" + "" + off + ""};
var msg2 = { payload: "" + id + "" + "f01" + "" + off + ""};
var msg3 = { payload: "" + id + "" + "f02" + "" + off + ""};
 

if (status == true) {
    return [msg1, msg2, msg3];
}

Also as a rule you shouldn't be creating new msg objects in function nodes, it is best practice to reuse the original input message where possible as the object may be carrying other values that are required down stream on the flow (e.g. the http-in and http-response nodes require that the original msg object make it all the way down the flow)

What is the purpose of the double 'double' quotes ""?
Doesn't the following give the same result?

var msg1 = { payload: id + "f00" + off };

Probably, I was answering from my phone so copy/pasted and made the minimal edit

Hello, thank you very much for your answer, it works perfectly for the action I want to perform.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.