Confusion about global variables

I tried to set both flow and global variables and I don't think I properly understand how they function. For example, I have a flow that sets a global variable global.GlobalTherm.Temp. When I inject the global variable into a debug using:

[{"id":"120c2b43.843be5","type":"debug","z":"30882327.2d261c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":440,"y":520,"wires":[]}]

I get { Temp: 65 } which means it's clearly getting stored. However, whenever I try to do anything with that variable, I get a type error. For example:

[{"id":"69b204b.37764fc","type":"function","z":"30882327.2d261c","name":"convert to f","func":"global.GlobalTherm.Diff = global.GlobalTherm.Temp-10\nreturn global;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":550,"y":720,"wires":[["5f0f5493.5ed0ac"]]}]

yields: "TypeError: Cannot read property 'Temp' of undefined". I think I'm just confused about how node red uses global variables, etc. Can someone explain what exactly I'm doing wrong?

In your function node, you need to use global.get('GlobalTherm') instead of global.GlobalTherm.

Here are the docs for reference: Writing Functions : Node-RED

Also, to return the global value from your function node, your can't just return it as is, but return a proper message object.
Just modify the payload of the existing message, something like this should work

let temp = global.get('GlobalTherm');

temp.Diff = temp.Temp - 10;

msg.payload = temp;

return msg;

Be aware that this will return a reference to the same object as in the global context, not a copy. So downstream nodes could work with different data, if other nodes modify the object in the global context.

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