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.getSignedU
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);
}
});
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