Nan*_*nam 4 amazon-s3 node.js aws-sdk
我目前正在尝试使用 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)
}
Run Code Online (Sandbox Code Playgroud)
我还尝试使用回调:但是,似乎从未输入过所述回调。这是我的代码的样子:
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")
Run Code Online (Sandbox Code Playgroud)
使用此代码,“我们在回调中”从未出现,而“我们不在回调中”正确出现。
无论我做什么,都不会发现任何错误。根据我对函数应该如何工作的理解,如果文件不存在,它应该抛出一个错误(然后被我的 catch 捕获),从而允许我不使用 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
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4040 次 |
最近记录: |