I'm trying to create a flow context variable in a Function Node to store an array which will be dynamically filled or emptied according to some logic. Unfortunately, it seems that the context variable does not work as I was expecting.
This is a minimal code to reproduce what I'm trying to do:
//Set the flow var with an empty array
flow.set("test_var", [])
// Update the flow variable
flow.set("test_var", flow.get("test_var").push(5))
// Store flow var in msg.payload
msg.payload = flow.get("test_var")
return msg;
Looking at the code, I was expecting my msg.payload equal to [5] but, the returned result is a number (1).
The return value of javascript's push is the new length of the array, and this what you are then setting to test_var again.
If you store an object in flow context, you don't need to keep storing it every time you change it. So your code can be simplified to:
flow.set("test_var", [])
// Update the flow variable
flow.get("test_var").push(5)
// Store flow var in msg.payload
msg.payload = flow.get("test_var")
return msg;
That only applies for the default memory based context. Generally it is good practice to store it back. If a switch was made to using persistent storage (or other storage mechanism) then it may not work reliably if it is not written back after updating.