Create and call a Node JS module - austral-electronics/Austral_Support GitHub Wiki

^ Back to Node-Red

Tutorial :

Create a simple open source node JS module called from Node-red
 cd ~/git
 mkdir private_module
 cd private_module

Initialize the NPM

 npm init
 package name: (private_module) private_module
 version: (1.0.0) 
 description: Quantum private module
 entry point: (index.js) 
 test command: 
 git repository: 
 keywords: 
 author:
 license: (ISC)

Edit index.js

 module.exports = {
    sum: function(a,b) {
        return a+b
    },
    multiply: function(a,b) {
        return a*b
    }
 };

Install the private module in node-red:

 cd ~/.node-red
 npm install ~/git/private_module

The installed module is in :

 cd ~/.node-red/node_modules/private_module

Add the module to the Node Red functionGlobalContext, edit settings.js :

 nano settings.js

Add :

 functionGlobalContext: {
      myTools:require("private_module"),
      ...

Relaunch node red:

 node-red-stop && node-red-start

Create a node-red test function:

 const myTools = global.get('myTools');
 msg.payload=myTools.sum(10,20);
 return msg;

Add an inject and debug function to test your module :

 msg.payload : number
 30
⚠️ **GitHub.com Fallback** ⚠️