I need to check if a file exists using AWS SDK. Here is what I'm doing:
var params = {
Bucket: config.get('s3bucket'),
Key: path
};
s3.getSignedUrl('getObject', params, callback);
It works but the problem is that when the object doesn't exists, the callback (with arguments err and url) returns no error, and when I try to access the URL, it says "NoSuchObject".
Shouldn't this getSignedUrl
method return an error object when the object doesn't exists? How do I determine if the object exists? Do I really need to make a call on the returned URL?
To check whether a bucket already exists before attempting to create one with the same name, call the doesBucketExist method. It will return true if the bucket exists, and false otherwise. if (s3. doesBucketExistV2(bucket_name)) { System.
Another way to verify the integrity of your object after uploading is to provide an MD5 digest of the object when you upload it. If you calculate the MD5 digest for your object, you can provide the digest with the PUT command by using the Content-MD5 header.
You can use S3 Versioning to keep multiple versions of an object in one bucket and enable you to restore objects that are accidentally deleted or overwritten. For example, if you delete an object, instead of removing it permanently, Amazon S3 inserts a delete marker, which becomes the current object version.
Before creating the signed URL, you need to check if the file exists directly from the bucket. One way to do that is by requesting the HEAD metadata.
// Using callbacks s3.headObject(params, function (err, metadata) { if (err && err.name === 'NotFound') { // Handle no object on cloud here } else if (err) { // Handle other errors here.... } else { s3.getSignedUrl('getObject', params, callback); // Do stuff with signedUrl } }); // Using async/await try { await s3.headObject(params).promise(); const signedUrl = s3.getSignedUrl('getObject', params); // Do stuff with signedUrl } catch (error) { if (error.name === 'NotFound') { // Handle no object on cloud here... } else { // Handle other errors here.... } }
The simplest solution without try/catch block.
const exists = await s3
.headObject({
Bucket: S3_BUCKET_NAME,
Key: s3Key,
})
.promise()
.then(
() => true,
err => {
if (err.code === 'NotFound') {
return false;
}
throw err;
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With