Question

I have created a sails service to load the javascript files depends on its controller name (or page and/or if there's a session).

I passed this (array of) JS files into an res.local.js and in my layout.ejs, loop it to include the js file into my html.

for (i = 0; i < loadJS.length; i++) {
 <script src="<%- loadJS[i] %>.js"></script>
}

Question, how can I check if the JS file exists before including it in my html?

In PHP, we have function called file_exists, is there a similar function with sails.js?

Était-ce utile?

La solution

Yes. Since Sails is created with Node.js you can use fs.exists.

This will remove the file from the array if it's not found. You can load it into your view how you were before.

fs = require('fs');

for (i = 0; i < loadJS.length; i++) {
    fs.exists(loadJS[i], function(exists){
        if(!exists){
            //remove from array
            loadJS.splice(i, 1);
        }
    });
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top