ONLY of interest if you are using Node-Red and will lead to a description of the new node-red-contrib-diode node.
If you are into Node-Red – you really want to see this one…
There I was messing about with a function in Node-Red… and I needed to send some data out – and then send it out again – don’t ask why…
This simple function sends out the message out of the output – then when it finishes – does the same thing again. I know, useless but I’m making a point here.
In the receiving function… I altered msg.payload… and why not – you’ve passed a message and can do what you like with it can’t you? Well, no.
As was pointed out to me the solution is simple – to do any messing about – make a COPY of the message. But as they are passed by reference, if you do that you STILL end up in trouble.
The answer is something like this..
var newMsg = RED.util.cloneMessage(oldMessage);
Well, that’s all very sensible – but WHERE THE HELL did that RED.util.cloneMessage function come from?? I’d never heard of it? Thankfully my friend Google was at hand. Check this lot out.
So here is an example fail…
What you see above is an injector (content irrelevant) – and two functions – the output of both are monitored.
The first node simply sends the same message to 2 outputs.
Simple enough – first to the first output and then to the second output. You might expect to see “hello” on the green debug node and most of the time you will.
However, because the message is passed by reference and not value, see that “edit msg” function? It merely contains this.
So when pressing that timestamp node you might expect to see “goodbye” followed by “hello” on the debug – but you WON’T – you’ll see “goodbye followed by “goodbye” because the actual sending message ITSELF has been altered. I can tell you – that caught me out the first time until it sunk in that all that is being passed is the address of the message – not the message itself.
Ok, as referred to in the comments, the above is something of an “edge” case – and now you understand that it is a REFERENCE that is passed you might avoid this – but one I think I’ve created this situation more than once and only now do I fully understand it thanks to readers.
So here is a simple solution if you can’t get your head around “reference” or you need the message to be isolated for some other reason…
The new “diode” node can be simply dropped in – and will effectively isolate the output by creating a copy of the message. If you find yourself in this situation, you will find this new node in the usual place. http://flows.nodered.org/ – just search for “diode”. As I write this it has not yet filtered down into the flows library but no worries, it is also here… https://www.npmjs.com/package/node-red-contrib-diode