Calling Environment variables as a Global variable name

Hello everyone,

I'm attempting to do the same thing as in the topic linked below :

Continuing the discussion from Calling Environment Variables in Change Node for Global Variable name:

let envr = env.get("evr_name") ?? "0";
msg["ArrayDefect" + envr] = msg.payload;
return msg;

I tried to apply this logic to create a global variable whose name originates from an environment variable but can't get it to work ; and the person at the end didn't explain how they succeeded :smiling_face_with_tear:

I would highly appreciate some help !

Thanks in advance.

Your code looks fine. what do you see when this runs? Did you try @E1cid first suggestion using a change node?
image

Can you provide a minimal flow and instructions that demonstrates your issue?

Thank you for your reply !

The global variable I wish to name isn't an array so using a change node wouldn't do the trick ; the provided code does function but only when setting a msg and not a global variable.

No one said your env var was an array, nor does that change node consider the env var to be an array.

That would be because that snippet of code is not designed to set global variables (by which I guess you mean set "global context" variable?)

That linked post was nothing to do with setting a global variable (whatever that is) so even if they did explain, it would not work for you.


One more try to help you.

1)

What are you actually trying to set and for what reason? What do you mean by "I tried to apply this logic to create a global variable"? Global Context? If yes, then a select global instead of msg in the change node!

2)

What I suspect you are trying to do is

  1. get a variable name from env var
  2. store msg.payload in global context with the name retrieved in step 1

If I am correct, then something like this...

const evrName = env.get("evr_name")
if (!evrName) {
  node.warn('evrName is empty!')
  return null
}
global.set(evrName, msg.payload)
return msg;

Sorry for not explaining thoroughly, I thought the topic I linked explained my issue well enough...

And in the original topic, someone mentioned the change node could be used if the global context variable is an array and to otherwise use a function node, which is why I added that precision.

That is exactly what I need.

Thank you ! And sorry again for not explaining my issue correctly.

For future reference, is there a way to do this with a change node ?
I don't know what the correct syntax is to call on an environment variable into a global context name.

Yes & No.

If you nest your global context variables in an object (which is always sensible as it makes managing lots of global variables easier) you CAN use a change node.

Example:
image

2 Likes

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