Using node js variables in the node red

I have embedded node red into node js. I want to use variables or objects created in the node js in the node red flow. What would be the way to achieve it?

First thing to note is that a Function node runs the JS code in a VM which protects it from the "outside world". That means that you probably need a custom node that exposes the data to your flows.

There are probably lots of ways to do this. But the key is to know at what context level the variable is defined. That tells you where the variable is available.

If you've just used var everywhere and have a fairly monolithic node.js app, you might be (unpleasantly) surprised what you can "see" from a custom node.

If you are using more modern techniques along with const & let and have split things up into separate modules as is best practice, pretty much nothing should be available by default.

The way I would probably normally go about this then is to put the data into a node.js module and to require it both from your outer app and from your custom node. Because require is clever, it will only ever load the module once.

I've recently started going beyond that and using "singleton" class modules. Check out web.js and socket.js in the newly release uibuilder v4 to see how they work. Basically, you both define and instantiate the class in the module so that when it is first required, the class gets instantiated and when you require it again, you simply get a reference to the same instance.

Within a class you can do all sorts of clever things such as having static variables (though they only probably make sense if you are not using a singleton) and, at least in node.js v14+, you will finally get private variables and classes.

You can do all of this without classes though if you prefer - just have a detailed look at how modules work and how you can have things both outside and inside the exported objects.

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