[英]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). 我创建了一个Sails服务来加载javascript文件,具体取决于其控制器名称(或页面和/或是否存在会话)。
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. 我将此(一组)JS文件传递到res.local.js中,并在我的layout.ejs中,循环将其包含到我的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? 问题,在将其包含在html中之前,如何检查JS文件是否存在?
In PHP, we have function called file_exists, is there a similar function with sails.js? 在PHP中,我们有一个名为file_exists的函数,sails.js是否有一个类似的函数?
Yes. 是。 Since Sails is created with Node.js you can use fs.exists .
由于Sails是使用Node.js创建的,因此可以使用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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.