This.context() VS this.context().flow in custom node


I would appreciate it if you could review the code at this link:

In line 15, I have to use this.context().flow instead of this.context() for the code to function correctly. When I use this.context(), I’ve noticed that the code sometimes executes node.status({ fill: "blue", shape: "dot", text: "waiting for trigger" }) (found in line 24), on unexpected moments. However, when I use this.context().flow, it only executes after the first deployment, as I would expect.

This is my first node and many things are new to me.
So it might be a silly question, but I really want to know why i can't use this.context() in my code.

Thank you in advance.


I have moved this to Developing Nodes - and its great to hear, another contributor is adding to the cause!

A few Pointers....

During the init phase (OperateLogicNode) I wouldn't attempt to output anything (Line : 23)

Node RED is still getting it's S**t together about this node during this phase, if you need to output anything at this early boot stage, add a delay (setTimeout)

This may extend to status I'm not entirely sure.

as for context.

  • this.context() - The nodes own context
  • this.context().flow - The context of the flow that the node lives (you cant use this for config nodes)
  • this.context().global - The global context

var VS, let VS const

Use const if the value never changes... BUT a mutable object still never changes its pointer, so still use const for these.

Use let not var if the value changes.

var can be (and is) troublesome in todays javascript estate

I know its not a direct answer, but some of the above, may leave a few bread crumbs.
My advice will be, if you are attaching to significant areas during the init phase, add a small delay with setTimeout

And Welcome to the Forums :smile:

Thank you for quick response. I will change the code to your pointers.

I have conducted further tests comparing this.context() and this.context().flow. The differences (and probems i have) between the two are now somewhat clearer. When I use this.context().flow, I can freely restart Node-RED or alter the node settings, and it will still function correctly. It retains its state.

However, if I switch the code to this.context() and perform the same actions, it seems as if its previous state is lost and it does not operate as anticipated.

There must be something that i've missed.

I found the cause.
I didn't realise that on my test system the contextstorage in settings.js was disabled.:face_exhaling:

So when i use this.context();flow it seems it stores the data over restarts of the flows?

New question:
Can i rely on this setting for developing nodes?

It depends what you mean by that. Each individual user will choose whether they have persistent context enabled or not - that is not something your node can enforce.