Using a client side JS file

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.

  1. In your project, add folders /static/, /static/js/ & /static/css/

  2. Add a "dumb" node-red node called (for example) app.js - this is the end point that serves files from /static/ to http://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);
      });
    }
    
  3. Add the associated html file app.html - this dynamically loads your files at client side (via the end point created in app.js)

    <script type='text/javascript'>
       $.getScript('image-tools/static/js/image_tools.js');
    </script>
    
  4. In package.json, add a node-red node pointing to app.js

    "node-red": {
        "nodes": {
            "app": "app.js",
            "xxx": "xxx.js"
        }
    },
    
  5. 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));
    
  6. To use the js client side, you simple access image_tools.getOptionsMap()

  7. 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.

2 Likes