Skip to content

Instantly share code, notes, and snippets.

@ruandre
Last active February 8, 2022 05:36
Show Gist options
  • Save ruandre/4079470e4a721f59c10536251851a333 to your computer and use it in GitHub Desktop.
Save ruandre/4079470e4a721f59c10536251851a333 to your computer and use it in GitHub Desktop.
Check if S3 bucket exists using AWS SDK JavaScript Node.js
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
const BUCKET_NAME = 'MyBucket'
async function main() {
try {
const data = await s3.headBucket({ Bucket: BUCKET_NAME }).promise()
return `Bucket "${BUCKET_NAME}" exists`
} catch (err) {
if (err.statusCode === 403) {
return `Bucket "${BUCKET_NAME}" Access Denied`
}
if (err.statusCode >= 400 && err.statusCode < 500) {
return `Bucket "${BUCKET_NAME}" Not Found`
}
throw err
}
}
main() // until https://github.com/tc39/proposal-top-level-await
@adi-endor
Copy link

adi-endor commented May 2, 2021

Hey there, I think you're missing a thing here
headBucket can return 403 which indicates that a bucket exists but your access denied

so condition at line 16 is not accurate :)

@ruandre
Copy link
Author

ruandre commented Jun 18, 2021

Ah good catch; have updated :)

@haydanu
Copy link

haydanu commented Aug 26, 2021

nice!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment