문제

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?

도움이 되었습니까?

해결책

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);
        }
    });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top