Is it possible to somehow refer to a function from the library of personal functions in the code of the node "function"?

Hello
Is it possible to somehow refer to a function from the library of personal functions in the code of the node "function" ?

Yes.

Store your functions in an object then store that in global or flow scope

const utilityFunctions = {
   myFunction: (x,y) {
     return x + y
   }
}
global.set('utilityFunctions', utilityFunctions)

Then in the other functions, get that back out of global scope...

const utilityFunctions = global.get('utilityFunctions')
msg.payload = utilityFunctions.myFunction(2,2) // 4
return msg

However, this is hiding the beauty of node-red.

Really, a better way would be to make each shared function (that you want to re-use) a function node and use the link-call node to call them. This makes (kinda) visual subroutines that you re-use.

2 Likes

I absolutely agree with you.
But in my case, about a hundred nodes are already used, several of which contain more than 200 lines of code, and one even more than 1000.

Thank you very much for your help !

The litlle problem:

The error turned out to be a typo:
there was:
myFunction: (x, y) {
need to:
myFunction: function(x, y) {

const utilityFunctions = {
    myFunction: function(x, y) {
        return x + y
    }
}
global.set('utilityFunctions', utilityFunctions)

//Then in the other functions, get that back out of global scope...
const utilityFunctions2 = global.get('utilityFunctions')
msg.payload = utilityFunctions2.myFunction(2, 2) // 4
node.warn('msg.payload =' + msg.payload)

return msg

Steve-Mcl

And why didn't you use ';' at the end of lines in your code ?

Habit. Personal preference.

I try to stick to eslint standard config

What is this "eslint" ?

It is a coding style.

https://standardjs.com/rules.html

Currently, node-red function node does not directly support eslint like Vs code does but I am now pretty used to using eslint that I tend to write the same style in node-red functions.

There is a separate linter you can install for node-red if you want code linting

1 Like

Steve-Mcl
It's very intresting information for me.
And what is the name of the coding style that is used in the "function" Node RED 3.1 nodes ?

I believe that node-red core coding tries to stick to JavaScript Standard but I'm not sure what, if any eslint settings have been used for the node-red Monaco editor element. I think that it tries to remain relatively neutral - so for example you can use ; or not or even a mixture and it doesn't complain. That is probably sensible for the range of people likely to use node-red.

1 Like

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