How to determine if object exists AWS S3 Node.JS sdk
by using headObject
method
AWS.config.update({
accessKeyId: "*****",
secretAccessKey: "****",
region: region,
version: "****"
});
const s3 = new AWS.S3();
const params = {
Bucket: s3BucketName,
Key: "filename" //if any sub folder-> path/of/the/folder.ext
}
try {
await s3.headObject(params).promise()
console.log("File Found in S3")
} catch (err) {
console.log("File not Found ERROR : " + err.code)
}
As params are constant, the best way to use it with const
. If the file is not found in the s3 it throws the error NotFound : null
.
If you want to apply any operations in the bucket, you have to change the permissions of CORS Configuration
in the respective bucket in the AWS. For changing permissions Bucket->permission->CORS Configuration
and Add this code.
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
for more information about CORS Configuration : https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html
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;
}
);
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') { // Note with v3 AWS-SDK use error.code
// Handle no object on cloud here...
} else {
// Handle other errors here....
}
}