There are a few ways to achieve this but ultimately you have to serve the code via an endpoint.
Here is an example from one of my nodes - I like this pattern as I can share the js with both client and server side.
-
In your project, add folders
/static/,/static/js/&/static/css/ -
Add a "dumb" node-red node called (for example)
app.js- this is the end point that serves files from/static/tohttp://xxxxx/image_tools/static/***module.exports = function (RED) { /** * Enable http route to static files */ RED.httpAdmin.get('/image_tools/static/*', function (req, res) { var options = { root: __dirname + '/static/', dotfiles: 'deny' }; res.sendFile(req.params[0], options); }); } -
Add the associated html file
app.html- this dynamically loads your files at client side (via the end point created inapp.js)<script type='text/javascript'> $.getScript('image-tools/static/js/image_tools.js'); </script> -
In package.json, add a node-red node pointing to
app.js"node-red": { "nodes": { "app": "app.js", "xxx": "xxx.js" } }, -
create your shared js file. NOTE: in order to be able to import it both server and client side, you need to be a bit clever. This is the basics...
(function(exports){ exports.getOptionsList = function(){ return []; //snipped for brevity }; exports.getOptionsMap = function(){ return {}; //snipped for brevity }; }(typeof exports === 'undefined' ? this.image_tools = {} : exports)); -
To use the js client side, you simple access
image_tools.getOptionsMap() -
To use the js server side, you require the file
const image_tools = require("./static/js/image_tools");
I dont think i missed anything but if I did, have a look through the source of node-red-contrib-image-tools where I employ this solution.