Nina
Nina

Reputation: 141

Check if file exists in sails.js

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?

Upvotes: 0

Views: 1211

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

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);
        }
    });
}

Upvotes: 1

Related Questions