Reusing msg object in Function requires cloning

I know, it's a good practice to reuse the input msg in a function but in this case it can be painful to find out what is going on.

If you reuse the msg in the following nodes, your first msg is also changed.

Try this example:

[{"id":"8def5c6a.3c9ad","type":"function","z":"66646ca8.e97654","name":"","func":"msg.payload = 'my msg is awsesome';\n\nnode.send(msg);\n// how to fix it\n// node.send(RED.util.cloneMessage(msg));\n\nmsg.payload += ', it can be changed outside of my function.'\n\nreturn msg;\n","outputs":1,"noerr":0,"x":290,"y":3600,"wires":[["e5378dfa.6fcb2","c799d2d2.10153"]]},{"id":"5258df92.76677","type":"inject","z":"66646ca8.e97654","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":140,"y":3600,"wires":[["8def5c6a.3c9ad"]]},{"id":"e5378dfa.6fcb2","type":"function","z":"66646ca8.e97654","name":"","func":"msg.payload = 'my msg is foobar';","outputs":1,"noerr":0,"x":450,"y":3600,"wires":[[]]},{"id":"c799d2d2.10153","type":"debug","z":"66646ca8.e97654","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":470,"y":3660,"wires":[]}]
1 Like

The runtime tries to minimise how much cloning it has to do when message objects are being passed around.

If you call node.send multiple times for the same object, then the runtime isn't able to recognise them as being the same object and won't know to clone them for you.

You need to clone it yourself with var newMsg = RED.util.cloneMessage(msg))

Thanks. That's what I did:

// how to fix it
// node.send(RED.util.cloneMessage(msg));

My apologies - I thought you were asking for help. Could you update the topic title to reflect the problem so others may find it in the future?

I see you have edited the title, but it still doesn't say anything about what the issue is. That isn't helpful.

I thought, this explains the issue:

If you reuse the msg in the following nodes, your first msg is also changed.

and the example shows you what happens.

But please correct me if it isn't clear.

I'm talking about the title of this thread:

I’ve spent a couple of hours to fix a strange issue (In case you get the same behaviour see the solution)

Anyone browsing the list of topics will have absolutely no idea what the issue is about - they will have to click into the thread and read your full post to find out.

A better title would be something like:

Reusing msg object in Function requires cloning