Before Christmas, my department at IBM had one of our semi-regular Hack Days to get everyone together and work on interesting ideas away from the day job. I spent the time playing with an idea to make exposing NPM packages in Node-RED easier…
Node-RED is a visual tool for wiring the Internet of Things.
It makes it easy to create, combine and control data flowing between hardware devices, web APIs and open protocols. The tool exposes operations through a series of nodes, which can be created through the browser-based editor and connected to other nodes to create message flows.
The tool comes built-in with a huge selection of nodes, from connecting to a Raspberry Pi to handling HTTP requests, for creating flows. Users create their own nodes to expose new functionality, by creating small modules using JavaScript and HTML. People often wrap existing NPM modules into custom Node-RED nodes to use that module functionality in flows.
NPM has over two hundred thousand modules, many of which provide simple “stateless” functions that return a result based upon the input data. These modules are ideally suited for using within Node-RED message flows.
Exposing multiple new NPM modules required creating custom Node-RED nodes for every module you wanted to use. Whilst the Node-RED node boilerplate is small, it becomes a bit laborious and repetitive to keep doing this for extremely simple modules.
Wondering how to make this easier, I started hacking on ideas.
Two days later…
Node-RED node to dynamically expose NPM modules as nodes. node-red-contrib-npm http://flows.nodered.org/node/node-red-contrib-npm
This new node allows you to dynamically expose NPM modules as Node-RED nodes without needing to manually create new nodes for them.
Using the node editor panel, the user can set the name of the NPM package to expose along with the module invocation style.
Incoming flow messages are passed as an argument to the function being executed. Users can set up the node to call the module, a module function or even run custom setup code in response to incoming messages.
Execution results, either returned directly or asynchronously (Promises and callback-style supported), are sent as the outgoing message payload.
When the flow is deployed, the NPM module will be automatically installed and instantiated.
Now we don’t have to write lots of extra boilerplate code every time we want to use a tiny NPM module in a Node-RED flow, hurrah!
Here’s a short demonstration using the node to expose the sentiment package in a flow: