Storing data in a flow function (persistent/context data)

Hi Fellow Node-RED fans,

I had a need to count some errors, which would increase each time a particular flow ran (and add on to the count from the last go-through).

I found some info about this in Terry’s nifty Node-RED videos.

His example, “Intro to Node-RED: Part 3 - Advanced nodes,” had just one of these what they call context variables (kinda like our persistent variables in PAC Control) which he initialized to 0 the first time it’s used/created, then incremented each time through the flow.

FYI, this example was based on the handy Node-RED documentation on NodeRed.org… in particular the Writing Functions part of the User Guide, where it shows you how to configure a flow variable (local to the flow, vs. the global “context” data which can be used across all flows):

However, that example had just one variable (the ‘count’ which is initialized there after the || as 0 in the beige box). In Terry’s example, he had a line of code in his function in increment that count, something like:

count++;

I had multiple counts I wanted to keep (7) and didn’t want to create a separate variable for each. So I figured out I could do a little array instead.

Compared to that one line of code in the beige box above, I have two lines (1 & 4 below.) I defined that array, called values, in line 1, which I assigned to the context data (called ‘errorCount’) there on line 4. The key for initializing it was to replace the 0 after the || with [0,0,0,0,0,0,0], as shown below, highlighted, line 4.

The rest of that code is just me looping through all 7 error counts and incrementing them in certain circumstances (on line 16). Much easier than having 7 separate count variables and checking each individually!

I’m likely to forget that syntax next week, and figured someone else could use it at someone point, so I thought I’d share. As always, we encourage you to share your own examples/discoveries, too!

If you’ve not already checked out Terry’s awesome videos, they’re highly recommended for all you Node-RED fans.

Code on…
-Mary