Using switch node

Hello

I am trying to implement some logic in my flow, to trigger one of two nodes based on the payload.

I am not sure which node to use for this. Basically the logic is:

image

var payloadmsg = "";
if (msg.payload.state_l4 != undefined) {
payloadmsg = { state_l3: "ON" }; // TRIGGER NODE #1 (AND NOT NODE #2)

} else {
payloadmsg = { state_l4: "ON" }; // TRIGGER NODE #2 (AND NOT NODE #1)
}


msg.payload = payloadmsg;

return msg;

What I need to do, is trigger a subsequent node if msg.payload.state_I4 is undefined, and another node if it is defined (shown as node 1 and 2 in the illustration)

The function node only has one output, so I can't use that. What node should I use for this?

You can add outputs to the function node in the setup tab, and can send messages to each output, all documented Writing Functions : Node-RED

Something like this should work, after you add the outputs

let output =  [];
let index;
let payloadmsg = "";
if (msg.payload.state_l4 != undefined) {
payloadmsg = { state_l3: "ON" }; // TRIGGER NODE #1 (AND NOT NODE #2)
index = 0;
} else {
payloadmsg = { state_l4: "ON" }; // TRIGGER NODE #2 (AND NOT NODE #1)
index = 1;
}


msg.payload = payloadmsg;
output[index] = msg;

return output;
1 Like

And remember to not “recycle” the same msg if sending to multiple outputs at the same time.
Create a new object for each, or at least derived from the incoming msg

This often fools people, as the msg is an object, so if you send to output 1, change it, then to output 2 - output 1 will see the changes - which you likely don't want

const Output1 = {
   ...msg
}

/* Manipulate Output1 */

const Output2 = {
   ...msg
}

/* Manipulate Output2 */

return [Output1, Output2]

/* Only Output1 */
// return [Output1, undefined]

What's wrong with the switch node?
image

2 Likes

Nothing, not a dam thing! :laughing:

Though this is not an issue in this case as it is only required to send to 1 output and not the other.

1 Like

Thanks heaps - the dual function node did the trick

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