Because node-red is a nodejs applications it is possible to use nodejs modules in node-red.
Depending on the version of node-red that you are using there are two ways of doing this:
- Editing the settings File -All versions
- Setup tab in the function node -1.3 and above
Settings File Changes
For example, If you need to use an node module e.g the os or fs module then you need to enable them under the functionGlobalContext: object as shown in the screen shot below:
To use them in the function node they are part of the global object so use:
in the function node.
When enabled via the settings file they are usable in any function in the workspace.
A setup tab was added to the function node in version 1.3. Add the external modules that the function node uses here as shown in the screen shot below.
To use then the function node there is no need to declare them as you need to do when they are enabled using the settings file.
When enabled via the setup tab they are only usable in that function node.
Example Using the os External Module
This module is used for getting information about the computer operating system and is described here.
We are going to use this module to get the current OS and the hostname of the computer.
Our function node code looks like this.
let os=global.get("os"); node.log("platform= " + os.platform()); node.log("hostname= " + os.hostname());
When using the settings file and like this when using the setup tab in the function node:
node.log("platform= " + os.platform()); node.log("hostname= " + os.hostname());
ASync and Sync Functions
Node-red runs in a single thread and all nodes run asynchronously.
This means that they do not block each other.
However function nodes can contain code that does block, and this is especially true when you use external modules.
As an example the fs module which gives access to the file system and lets you create folders,read and write files etc has sync and async versions of most functions.
As an example to create a directory you can use either the async call of
of the sync call of:
You may be thinking that the async call is always better, but if you have in your function node that does something like this
1.create new folder
2.write a file to the new folder
You may find that you are trying to write a file to a folder that doesn’t yet exist if you use the async version.
See here for ideas of how to run async functions and wait for results.