Search code examples
javascriptnode.jsglobal-variablesnode-red

How do I create a dynamically named global variable?


In Node-RED I am trying to create a global variable from a part of an MQTT topic:

var mytopic = msg.topic;
shortcode = mytopic.replace(/.*presence\/(.*)/, '$1');
global.set(shortcode, '1');

The documentation mentions global.set('foo', 'bar'); but how do I set the variable name, foo, dynamically?


Solution

  • Thank you for the replies.

    As suggested it should actually work and it does. My error lay elsewhere. I am aware of the risks of using global variables. Now I can work with MQTT topics like '+/presence/#' (containing information about the presence of different items detected by several sensors) with one flow.