Function Node "On Start" Tab


I am looking for examples on how to use the 'On Start' tab in a function node.

Can I use it like Arduino 'Void Setup()'? For example (and my example does not work), can I put in 'On Start' something like this:

static int number = 0;   // (like a static in other languages)

And then in 'On Message' something like this:

number = number + 1;

And now expect the number to be updated each time the node receives a message?

Or should I use flow.get and flow.set with the variable initially set in a 'set defaults' function run by a inject node at start up?

I'll admit that I've never found a use for it myself.

It runs when Node-RED starts so that is only once. There is no direct carry-over from on start to the main function so, yes, you need to use context/flow/global variables in order to pass data over.

Thanks.... I wonder why data is not carried between on start and on message?

Anyway, I will change to use context variables rather than flow - so thank you for that.....

For the same reason they are not carried between successive on message events. On start is just an initial event which is automatically triggered on startup.

1 Like

Either what you state is not entirely correct or the documentation is wrong:

Writing Functions : Node-RED states
"[...] the Function node provides an On Start tab [..] where you can provide code that will run whenever the node is started."

I understand it would also run upon redeployment of a node.

  • On Start code runs when Node-red starts up.
  • On Stop and On Start code runs when you make a significant change to that node (eg wiring the output to a debug) and deploy.
  • On Stop and On Start code runs when you do a full deploy.
  • If you make a trivial change such as moving the node or connecting a wire to it's input and deploy, neither run.
  • On Stop code does not run on sudo systemctl stop nodered

I suppose you could set global variables in the On Start code of the first function in the first flow and be reasonably sure they are in place.

My bad. You are correct I believe. I should have been clearer in my wording.

OK, I'l slink away quietly and contemplate my sins now .... :grin:

I don't think that is correct.
Run node-red-log in one window and in a different window run sudo systemctl stop nodered and see what appears in the log window.

Yes, it shows up in node-red-log.

A node.warn() statement in On Stop does not show up in the editor though.
Presumably the browser connection is already cut by that time.

That seems likely, yes. The important thing is that is is run so that it can release any resources it might have grabbed.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.