How to determine if object exists AWS S3 Node.JS sdk
Solution 1:
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....
}
}
Solution 2:
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;
}
);
Solution 3:
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
Solution 4:
You can also use the waitFor
method together with the state objectExists
. This will use S3.headObject()
internally.
var params = {
Bucket: config.get('s3bucket'),
Key: path
};
s3.waitFor('objectExists', params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Solution 5:
Use getObject
method like this:
var params = {
Bucket: config.get('s3bucket'),
Key: path
};
s3.getObject(params, function(err, data){
if(err) {
console.log(err);
}else {
var signedURL = s3.getSignedUrl('getObject', params, callback);
console.log(signedURL);
}
});