Fork Node or Clone Node?

Hi There!

I'm doing some UML2Node-RED flows and I came across a UML node that Node-RED doesn't seem to have and that is the fork node. A fork node receives one message and clones that message to each of it's output ports. Is there a an equivalent node in Node-RED?

I simulated the node using a function node with 4 outputs (because I needed 4 outs) and the following code:

return [
    { ...msg },
    { ...msg },
    { ...msg },
    { ...msg }
];

definitely not rocket science!

An alternative would be to use some sort of clone node (i.e. duplicate a message X times into an array) and then use the split node. The individual messages won't be the same since the split node assigns a parts attribute to the msg object, but that can be ignored.

Am I overseeing something and there is a fork node?

Cheers!

Reading this, would just adding four wires to the function output create four cloned messages?

Ah of course, what am I saying! I think my brain had a meltdown - it's just four wires from a node - doh!

Ok, sorry for my sunday morning meltdown :crazy_face:

@gregorius The good news is that you helped me to avoid cloning. I am working on a flow that is sending much pixel buffer data over websockets and forgot to add the false in node.send(). This could have been a costly oversight on my part.

@E1cid Thanks for the link to inform us. It seems that it does not explain that using return msg will or will not clone the first message, as was resolved here.

1 Like

Maybe i should of worded my post , would just adding four wires to the function output create the OG message plus three cloned messages? that may have been clearer. But cheers for clarification for future readers.

1 Like

I also create a Node-RED learning out of this meltdown, so it did have a happy end in the end!

1 Like

Ah, but .... :slight_smile:

You didn't mention shallow vs deep cloning.

By default, JavaScript will only ever shallow clone as far as I know. To deep clone requires something extra. Which is why Node-RED has a utility function to do just that.

Deep copy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)

RED.util.cloneMessage(..) : safely clones a message object so it can be reused

1 Like

Ah thanks for that, I forgot about that - flow updated

One last thing to mention is structuredClone. I used it recently on some client side js in a web component, but it is also available on the server side as of node.js v17. It seemed to work ok. Sounds like something that can be tested/compared.

1 Like

Certainly something that should be revisited once Node-RED hits node.js v18 as its minimum requirement.

Also, should only be used in the browser if you are sure you will only ever have browsers newer than early 2022 (Safari got this in March 2022, Chrome/Edge in Feb 2022, Firefox in Nov 2021).

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