Is it okay to use global Javascript functions?

I have a few utility Javascript functions (eg. formatting date/time) that are used by a number of flows. At the moment I’m using global.set to store them, and global.get any time I want to call them. The storing gets kicked off every time Node Red ‘restarts’ with a Deploy. All seems to be working fine, but is this the best way to do it? The documentation refers to storing variables in global, but doesn’t mention any restrictions about what those variables can contain.

Hi @michaelblight - in the next release we’re adding the ability to save the contents of context between restarts of Node-RED. If you enable this feature, it will only work for types that can be converted to JSON - which Functions cannot be. If you don’t enable the feature then everything is stored as-is in memory and it’ll continue to work.

So what you are doing is okay - unless you want to make use of persistent context in the future. If that’s the case, then there are a couple different approaches you could use.

  1. use functionGlobalContext in your settings file to pre-seed global context with your Functions. That saves you from having to inject them every time.

  2. or, use the older syntax = function() { ... } rather than the get/set functions. This will ‘attach’ your function to the global context object without it going into the persistence code.


Is it not possible to put the functions in settings.js rather than saving at run time?

@Colin not sure which of us that is aimed at. You’ll note my option 1 was to do exactly that.

Ah yes, so it is. I had missed that somehow.

@knolleary - Thanks for the info. I thought the settings.js path might be an option, but I’m not too keen on it because I’ll forget it exists and 6 months down the track spend way too long trying to figure out how the magic functions are working. I’m also not keen on anything referred to as “old context” for fear of it being deprecated while I’m not looking. The benefit in having it in a startup flow is that it’s there in front of me all the time, and as long as it’s a reasonable solution, I’m happy. Node Red is excellent btw - I wouldn’t have survived Home Assistant without it.

I realise I called it ‘old context’ but it was the way to use context for some time, so there will be lots of flows that use that syntax. We have absolutely no plans to remote or deprecate it - the introduction of persistent context actually makes it even more certain to stick around for exactly this sort of use case.

1 Like