Is the scope of "const" only within the node?

Hi Everyone,
I've spent most of today trying all sorts to get to the bottom of this.

I am familiar with context variables, however I want several flow.const
I can declare a const="Test" within a function node and it works no problem.
How do I declare a const to be flow or global? Is it possible?

Cheers.
Paul.

The only syntax for getting or setting context values (in a function node) is as per the docs:

flow.set('keyname', value)
...
var a = flow.get('keyname')

If you want to assign a context value to a const variable in a function node, you'd do:

const a = flow.get('keyname')

But that const variable is only in scope within that one Function node.

While I'm sure this is more about context.get rather than `const. Just in case it isn't ...

Strictly speaking, const and let are block scoped as I understand it. So they are always only in the scope of the function node but if you define them inside a block in the function node, they would be scoped only to that block and any other blocks within it.

const a = 3.141592654

if ( a > 0 ) {
   const a = 'fred'
   node.warn({a})
}

node.warn({a})

Gives:

image

Thank you both for replying.
I understand context variables, but what I was looking for is a flow or global const.
I realise that it's not available.

Is there any way of having header files?

Cheers.
Paul.

If you want to define a constant then you could do it under functionGlobalContext in your settings file.

https://nodered.org/docs/user-guide/writing-functions#global-context

1 Like

As Nick has indicated, you can set a global constant in the settings.js file which is only loaded when Node-RED starts.

In that file, you can also do something similar to header files by requiring external packages.

Here is an extract from one of my instances of Node-RED

    /** The following property can be used to seed Global Context with predefined
     * values. This allows extra node modules to be made available with the
     * Function node.
     * For example,
     *    functionGlobalContext: { os:require('os') }
     * can be accessed in a function block as:
     *    global.get("os")
     */
    functionGlobalContext: {
        pid: process.pid,
        _env: process.env,  // Pass environment vars to Node-RED
        userid: process.env.user || process.env.username || process.env.USER,
        userHome: process.env.home || process.env.userhome || process.env.HOME,
        require: require,   // DANGER Will Robinson!
        //_: require('lodash'),
        wiser: require('node-drayton-wiser')(),
    },

As you can see from the last entry, you can use Node.js's package management capabilities to load modules into the global variable store.

settings.js is just another node.js module itself and is loaded by Node-RED at startup.

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