'Passing Common Functions through Global Context In Node Red Dataflows

There are multiple data-flows in our application configured through Node Red. There are some common functions like date/currency formatting which are used across the flows such as below.

function formatCurrencyValues(value, isoCurrencyCode, lang){
    return new Intl.NumberFormat(lang, { style: 'currency', currency: isoCurrencyCode, currencyDisplay: 'code'}).format(value);
}

function formatDate(locale,date){
    return new Intl.DateTimeFormat(locale).format(date);
}

Is it possible to define these functions at a global level and call them wherever required?



Solution 1:[1]

Yes you can define functions in the settings.js under the functionGlobalContext section,

   ...
   functionGlobalContext: {
        formatCurrencyValues: function (value, isoCurrencyCode, lang){
            return new Intl.NumberFormat(lang, { style: 'currency', currency: isoCurrencyCode, currencyDisplay: 'code'}).format(value);
        },
        formatDate: function(locale,date){
           return new Intl.DateTimeFormat(locale).format(date);
        }

    },
    ...

And use them as follows:

var formatCurrencyValues = global.get('formatCurrencyValues')

var foo = formatCurrencyValue(msg.payload, 'GBP', 'en-gb')

Solution 2:[2]

In a node-red project, with many flows, I use the following method to create global singleton objects and function libraries (see also https://discourse.nodered.org/t/is-it-okay-to-use-global-javascript-functions/1306/2). Example:

foo{
  value = 3;
  getValue = function() {return this.value};
  }

I set in global context the 'data' part only at the start (e.g. in 'On start' or using a 'config node'):

   `global.set("foo",{"value"=3});`

Then I put the 'function code':

   context.global.foo = global.get("foo");
   context.global.foo.getValue = function() {
        return this.value};

USE in any function-node:

let bar = context.global.foo.getValue();

Advantages:

  • No external files, no 'settings file' updates.
  • foo is accessible by any function-node and any flow.
  • foo is visible in global 'context data' debug pad.
  • The function code is easily debuggable.

Hoping this will help.

m.s.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hardillb
Solution 2