Creating and Using Local Nodes in Node and Node-RED

 

This is pretty tricky because nodes published locally need to be installed from a local repository in order for require() to work. To use modules in Node-RED, modules need to be installed in ~./node-red/node_modules, which means the modules are 2 different places. This prevents testing w/o using a Node-RED flow.

Node will pick up modules from NODE_PATH, so setting as such:

 

export NODE_PATH=$(echo ~/.node-red/nodule_modules)

 

will tell node to look for modules where they are installed for Node-RED.

Publishing a Module

 

Create the module:

 

mkdir test-module
cd test-module
npm init

 

Create the index.js file:

 

exports.hello = function() {
    console.log("hello from test-module");
}

 

Don't Publish the module, just install it

 

 

a=$(pwd)/test-module
(cd $NODE_PATH;npm install $a)

 

Note: npm ls won't show it. It will only show modules in -g or ./node_modules, so use a symlink:

 

ln -s $NODE_PATH
npm ls

 

The module is now installed and available to require().

Test it

 

Create a test file, test-module.js:

var tm = require('test-module');
tm.hello();

 

Test it:

node test-module.js

 

That's it. To make changes and test them:

(cd $NODE_PATH;npm install $a)
node test-module.js

 

Install to Node-RED

 

Add this entry to ~/.node-red/settings.js:

 

functionGlobalContext: {
    // os:require('os'),
    fs:require("fs"),
    tm:require("test-module")
},

 

Test in Node-RED

 

Add any node to a flow with this code in it:

var tm = global.get("tm");
tm.hello();

Restart Node-RED.

^C
node-red

Trigger the flow, expect the output of hello() on the console.

To make an update use:

(cd $NODE_PATH;npm install $a)
node test-module.js
node-red

Test by triggering the flow.