Sailsjs - Dynamically load js

--> I use sails 0.10.9

I'm trying to load client-side javascript based on the route and controller name, and I want to control if the file exist before including it.

I thought I could use

req.options.controller
req.options.action

with a middleware in http.js but it's always empty.

So, how do you think I should do ? The aim is to inject the javascript file if it exists. I've tried with a policy with :

'*': 'loadScript'

But it doesn't load on other page than /

Any help would be really appreciate

The policy is the correct solution; the thing you have to remember about policies is just that they only apply to controller actions, not views. So if you have in your config/routes.js file:

"/myPage": {view: "myView"}

then the policy won't apply when you visit /myPage. Instead, you could do:

"/myPage": "StaticController.myView"

and in api/controllers/StaticController.js:

myView: function (req, res) {
    res.view("myView");
}

Then the policy will be applied.

Alright, thanks to @scott-gress for leading me to the good way, here is how I did it.

In api/policies/serveStatic.js

var fs = require('fs');
module.exports = function(req, res, next) {
    if(fs.existsSync(sails.config.local_config.js_dir_path + '/' + req.options.controller + '/common.js'))
        res.locals.scripts.push(sails.config.local_config.js_public_path+ '/' + req.options.controller + '/common.js')
    if(fs.existsSync(sails.config.local_config.css_dir_path + '/' + req.options.controller + '/common.css'))
        res.locals.styles.push(sails.config.local_config.css_public_path+ '/' + req.options.controller + '/common.css')
    if(fs.existsSync(sails.config.local_config.js_dir_path + '/' + req.options.controller + '/' + req.options.action + '.js'))
        res.locals.scripts.push(sails.config.local_config.js_public_path+ '/' + req.options.controller + '/' + req.options.action + '.js')
    if(fs.existsSync(sails.config.local_config.css_dir_path + '/' + req.options.controller + '/' + req.options.action + '.css'))
        res.locals.styles.push(sails.config.local_config.css_public_path+ '/' + req.options.controller + '/' + req.options.action + '.css')
    next();
};

And in config/policies.js

UserController: {
  '*': ['isAuthenticated', "serveStatic"]
},

after that, at the end of my views/layout.ejs file :

<% if(res.locals.scripts) { %>   
    <% res.locals.scripts.forEach(function(script, i ) { %>
        <script src="<%= script %>" ></script>
     <% }) %>
<% }%>

The advantage of that is that in any action, I can add my own js script (or css) if I want to.