Search code examples
node-red

Global value changing content when setting another variable with the global variable content


If you look at the following example you could see that I'm setting a global value on startup. After that, If you click inject module you'll see that I set to 22 the tag_id attribute of the object on a new value. I don't understand why the global object changes the tag_id value to 22 if I'm setting the value in another variable. I don't want that the global value change.

[{"id":"a1dc09e7.208b48","type":"function","z":"81ac975c.542c88","name":"","func":"var o = global.get(\"machine\");\nnode.warn(o[1]);\no[1].tag_id = 22;\n\n","outputs":1,"noerr":0,"x":350,"y":320,"wires":[[]]},{"id":"4cca337d.f22bfc","type":"inject","z":"81ac975c.542c88","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":"5","x":140,"y":320,"wires":[["a1dc09e7.208b48"]]},{"id":"fd1f90c5.86b85","type":"inject","z":"81ac975c.542c88","name":"Startup","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":true,"x":140,"y":220,"wires":[["950e20e9.dd2d3"]]},{"id":"950e20e9.dd2d3","type":"function","z":"81ac975c.542c88","name":"","func":"msg ={\n\t\"1\": {\n\t\t\"timestamp\": \"\",\n\t\t\"tag\": \"\",\n\t\t\"tag_id\": 0,\n\t\t\"value\": 0,\n\t\t\"units\": \"\"\n\t}\n}\n\nglobal.set(\"machine\",msg);\n\n//return msg;   ","outputs":1,"noerr":0,"x":350,"y":220,"wires":[[]]}]

Solution

  • This is an undesirable consequence of JavaScript passed objects by reference, not value. When you retrieve the object from Context you are getting ahold of the reference to the object in context. Any update you made is then reflected in context.

    If you want to change the object without modifying the original, you need to clone it:

    var o = RED.util.cloneMessage(global.get("machine"));