It's probably not news to anyone willing to read documentation, but I was able to simplify a number of Node-Red flows recently after a primer on context.
In Node-Red, each function node has a self-contained context. Variables are local to that node and nothing is permanent. Unless you use a different context.
It is possible to set flow-level and global-level variables that can be used to store values, provide them to multiple other nodes without links, and give the illusion of memory to Node-Red.
Setting flow context uses simple syntax:
In Node-Red, each function node has a self-contained context. Variables are local to that node and nothing is permanent. Unless you use a different context.
It is possible to set flow-level and global-level variables that can be used to store values, provide them to multiple other nodes without links, and give the illusion of memory to Node-Red.
Setting flow context uses simple syntax:
- flow.set('name of the variable', 'value of the variable')
This new flow-level variable can be called anywhere in the same Flow tab. This is great for recording values that don't change every time the flow runs (e.g. a maximum recorded value), or need to be used in isolation from the pathway that generates them.
Calling the value is relatively simple as well:
- var varName = flow.get('name of the variable')
To use the value, it makes sense to associate it to a local variable, but it's not necessary (though probably best practice to do so). The variable varName now has the value 'value of the variable', per the earlier example.
If you're not sure there will be a value associated to flow variable, you can declare a default initial value:
- var varName = flow.get('name of the variable')||'initial value'
The same usage applies to global context (global.get, global.set), but these values exist throughout your Node-Red instance, allowing flows to share variables. I haven't needed this myself, but the power of cross-communication is clearly significant.
So, relatively simple, but it adds a lot flexibility and has helped me reduce the visual spaghetti that complex flows can become.
Comments
Post a Comment