当对象不存在时,头对象永远不会引发错误



我目前正在尝试检查文件是否存在,使用 Amazon s3 的 aws-sdk(更准确地说,函数 headObject)。

正如我几乎可以在任何地方阅读的那样,这是在尝试检查文件是否存在时应该使用的函数(以便通过getSignedUrl获取其URL),但是我无法使其工作。

似乎,无论我做什么,函数 s3.headObject 都会告诉我该对象存在。我尝试检查现有项目、非现有项目,甚至在不存在的存储桶中:所有这些都让我得到了完全相同的输出。我尝试了不同的调用函数的方法(异步与否,是否使用其回调),但没有区别。

以下是我实现对函数的调用的方式:

var params = {
Bucket: 'BUCKET NAME',
Key: ""
}
// Some more code to determine file name, confirmed working
params.Key = 'FILE NAME'
try {
s3.headObject(params)
// Using here the file that is supposed to exist
} catch (headErr) {
console.log("An error happened !")
console.log(headErr)
}

我也尝试使用回调:但是,似乎从未输入过所述回调。这是我的代码的样子:

var params = {
Bucket: 'BUCKET NAME',
Key: ""
}
// Some more code to determine file name, confirmed working
params.Key = 'FILE NAME'
s3.headObject(params, function(err: any, data: any) {
console.log("We are in the callback")
if (err) console.log(err, err.code)
else {   
// Do things with file
}
})
console.log("We are not in the callback")

使用此代码,"我们在回调中"从未出现,而"我们不在回调中"正确显示。

无论我做什么,都不会发现任何错误。 根据我对函数工作方式的理解,如果文件不存在,它应该抛出错误(然后被我的捕获捕获),从而允许我不使用 getSignedUrl 函数创建错误的 URL。

我在这里做错了什么?

谢谢大家的回答。如果您有其他问题,我将非常乐意尽我所能回答。

这是使用async/await语法检查对象存在的正确方法:

// Returns a promise that resolves to true/false if object exists/doesn't exist
const objectExists = async (bucket, key) => {
try {
await s3.headObject({
Bucket: bucket,
Key: key,
}).promise(); // Note the .promise() here
return true; // headObject didn't throw, object exists
} catch (err) {
if (err.code === 'NotFound') {
return false; // headObject threw with NotFound, object doesn't exist
}
throw err; // Rethrow other errors
}
};

我确实尝试了语法,但它不起作用。它在我的 lambda 函数中。

参数和参数2 是预定义的存储桶和键集。

var url = s3.getSignedUrl('getObject', params);
const objectExist = async (par) => { 
try{
console.log(s3.headObject(par).response); //I honestly couldn't find any 
//section in the resoonse,
// that make a DNE file different from a existing file.
const ext = await s3.headObject(par).promise((resolve, reject) =>{
console.log("bbbbbbbbbbb");
if(err) { // it keeps saying the err is not global variable. 
//I am wondering why this is not defined.
//Really had no idea of what else I could put as condition.
console.log("aaaa"); //never reach here.
return reject(false);}
return resolve(true);
});
console.log(ext); //always true. 
if(!ext){url = url = s3.getSignedUrl('getObject', params2, callback); }
}catch(err){
console.log("reeeeeeeeee"); //when the method failed it execute. 
url = s3.getSignedUrl('getObject', params2, callback);
console.log(url); //even though I am sure that params2 are valid key, but url in the log always returned undefined.
}

};
objectExist(params);

最新更新