Import your own functions into a function node

Hi All,

Is there any easy way that I can import my own functions and use them inside a function node?

So for example I have a function A that will take in a value do some logic and return a value B. I would like to be able to use this function A in multiple the function nodes across the project. So if needed, I could edit the logic of function A and then it returns a new value C and this new logic can be applied across all the function nodes.

Just wondering how this can be done easily and how the editing of the function A can be done easily as well.

There are at least a couple of ways.

The "traditional" way is to set your function up in a node.js module. This means simple "exporting" the function and doing a require of that module in Node-RED's settings.js file.

mymodule.js

module.exports = {

   function myfn1(someParam) {
      // .... my code ...
   }

   // ... more functions if you want to ...

}

In the globals section of settings.js

    myStuff = require('./mymodule'), // this assumes you put the file in the same folder as settings.js

THen in your function node, you can do:

const myStuff = global.get('myStuff')

myStuff. myFn1(blah)

If you want shorted function names:

const { myFn1 } = global.get('myStuff')

myFn1(blah)
1 Like

Thank you so much for the reply.
I will try it out :grinning:

The more "low code" way (and runtime editable) would be to put your common function into a function node and "call" it using the link-call node.

1 Like

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