EXAMPLE - using an external javascript in a function node
This example show how to use an eternal NPM javascript in a function node. This example uses tinycolor.js to test an RGB color to see if it is 'light' or 'dark'.
** Setup **
- Go to the node-red directory
cd .node-red
- Install tinycolor.js
npm install tinycolor2.js
- Backup your settings file incase something goes wrong.
cp settings.js settings.bkup
- Edit
settings.js
and find the sectionfunctionGlobalContext: {
it should look like this
functionGlobalContext: {
// os:require('os'),
// jfive:require("johnny-five"),
// j5board:require("johnny-five").Board({repl:false})
},
add the following tinycolor: require('tinycolor2'),
to the begining so you will have:
functionGlobalContext: {
tinycolor: require('tinycolor2')
// os:require('os'),
// jfive:require("johnny-five"),
// j5board:require("johnny-five").Board({repl:false})
},
NOTE: if you have more than one entry, all but the last need a comma at the end.
- Save the file and restart NR. If the restart get an error, re-edit settings.js and make sure you don't have a typo.
In ** Node-RED ** in a function node you can now use the file
var tinycolor = global.get('tinycolor')
var color1 = tinycolor(msg.payload);
var t1 = color1.isDark(); // false
msg.payload = ("Is "+ color1 + " dark? "+ t1);
return msg;
here is a sample flow with two inject nodes sending #000 and #FFF
There are other things you can use in the function node like isLight()
and isReadable()
feel free to read about what you can do at https://github.com/bgrins/TinyColor
[{"id":"a61a8c88.442398","type":"inject","z":"cdaab1fb.ab33a","name":"","topic":"","payload":"#000000","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":200,"y":140,"wires":[["e8f2fcfe.764c3"]]},{"id":"d987f969.79c86","type":"debug","z":"cdaab1fb.ab33a","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":690,"y":180,"wires":[]},{"id":"e8f2fcfe.764c3","type":"function","z":"cdaab1fb.ab33a","name":"Check if color is light or dark","func":"var tinycolor = global.get('tinycolor')\n\nvar color1 = tinycolor(msg.payload);\nvar t1 = color1.isDark(); // false\nmsg.payload = (\"Is \"+ color1 + \" dark? \"+ t1);\nreturn msg;\n","outputs":1,"noerr":0,"x":440,"y":180,"wires":[["d987f969.79c86"]]},{"id":"5cfc8e7.a5d60f","type":"inject","z":"cdaab1fb.ab33a","name":"","topic":"","payload":"#ffffff","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":220,"wires":[["e8f2fcfe.764c3"]]}]