Been doing some changes to my Node RED flows and thought I’d share an interesting tool I came up with in case anyone is interested. I love subflows but one thing that bugs me a lot is that there’s no way to declare inputs which can be populated from msg data or JSONata expressions. Since the inputs are environmental variables they only allow design-time constants.
Thanks to the new prompting in function nodes though I found RED.util.prepareJSONataExpression
and RED.util.evaluateJSONataExpression
(@node-red/util_util - Documentation). This means you can allow JSONata expressions in places that don’t normally accept/understand them, like subflow inputs, and then evaluate them to a value at runtime.
So using that I made a quick subflow called Get env var
. This takes the name and value of an environmental variable which may contain a JSONata expression and evaluates it if so, sticking its value into msg.env.<env name>
. Since I also sometimes want to put constants I made a rule that if the value is prefixed with $:
then everything after the colon is evaluated as a JSONata expression, otherwise it just sticks the value in msg.env.<env name>
as is. This way I can just call this in my subflows for each env var that may contain expressions and then use the value in the rest of the subflow.
It’s… not pretty. Entering a long JSONata expression in a small textbox isn’t great since Node-RED doesn’t know JSONata is going there and won’t help you. But it works well for populating the value of a subflow input from a msg
field ike $:payload.a_field
or a small expression like $:$replace(payload.a_field, '_', ' ')
. Here’s the export if anyone is interested: