在检查 app/public 目录中是否存在文件时,此 Meteor 客户端代码无法返回 true。
当在浏览器控制台中使用时,如下所示,它返回undefined
utility.isFileExist('http://localhost:3000/abc.gif')
或
utility.isFileExist('http://localhost:3000/public/abc.gif')
为什么现在要修复它?谢谢
//client/lib.js
utility = (function() {
return {
isFileExist: (url) => {
$.get(url)
.done(function() {
return true;
}).fail(function() {
return false;
})
}
}
})();
根据评论进行编辑 请看这段代码
Template.checks.helpers({
'values': function() {
let result = [];
let checks = Session.get('items');
checks.forEach((item) => {
let url = item.replace(/[^0-9a-zA-Z]/g, '');
$.get(url + '.giiif') //<----- files do not exist
.done(function() {
console.log(`exists`); //<----- yet this prints out
}).fail(function() {
console.log(`does not exist`); //<--- expected this instead
});
result.push({
label: item,
image: url
});
});
return result;
}
});
最佳答案
首先,让我们找出问题所在:
utility
您发布的代码不起作用,因为 XHR 是异步的,因此您无法在 ES5 中使用同步操作(例如赋值)获取其值。
围绕该定义的 IIFE 是多余的。
isFileExist
方法本身不返回任何内容,如果返回,那将是请求的 jqXHR 对象,它不会为您提供调用时要查找的数据。
另一个问题是,对于任何未专门绑定(bind)到另一个响应的 URL,Meteor 通常会使用页面的 HTML 进行响应。这意味着该请求在技术上会成功(200 OK 响应代码,只是不是您预期的响应),因此 fail
在这种情况下也不会调用回调。
使用响应content-type
header 可能是判断结果是文件还是 HTML 文档的合理方法。
你可以这样做:
utility = {
doesFileExist(name, cb) {
$.get(name).done((data, status, request) => {
const isHtml = request.getResponseHeader('content-type') === 'text/html; charset=utf-8';
cb(!isHtml);
})
}
};
// call it with file name and a callback
utility.doesFileExist('foo.png', (doesExist) => {
if (!doesExist) {
// do something if file does not exist
}
});
它将独立工作,但不允许您按原样在模板助手中使用它。您也许可以使用ReactiveDict
它将跟踪请求状态,但它增加了代码的复杂性。
它的另一个缺点是,您需要为每个要检查的文件额外调用服务器一次。
<小时/>一些替代方案
每个<img>
标签应该有 alt
属性。如果图像丢失,alt
显示了文本,但这不太美观。
幸运的是,img
标签有 error
如果图像无法加载,则会触发事件,因此您可以使用它来隐藏图像或执行其他操作。
Template.foo.events({
'error img': function(e) {
$(e.target).hide(); //or something else
}
});
顺便说一句,您应该知道 public
中存在哪些图像。文件夹,因为它们是在编译时静态复制和提供的。
重要的是要在问题中解释您想要完成的任务,而不仅仅是问“我该怎么做 XY?” (因为答案的第一部分对于您的情况不是很有用)。
关于javascript - 检查 Meteor 公共(public)目录中的文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913528/