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?
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})
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.