如何使用aws-sdk测试AWS S3上是否存在存储桶?
此问题用于测试存储桶中是否存在对象:How to determine if object exists AWS S3 Node.JS sdk
这个问题适用于Python:How can I check that a AWS S3 bucket exists?
答案 0 :(得分:6)
您可以使用以下代码:
// import or require aws-sdk as AWS
// const AWS = require('aws-sdk');
const checkBucketExists = async bucket => {
const s3 = new AWS.S3();
const options = {
Bucket: bucket,
};
try {
await s3.headBucket(options).promise();
return true;
} catch (error) {
if (error.statusCode === 404) {
return false;
}
throw error;
}
};
重要的是要意识到如果存储桶不存在,错误statusCode
将为404
。
答案 1 :(得分:2)
要测试存储桶是否存在,请从createBucket回调方法中检查statusCode属性。如果是409,则说明它是以前创建的。我希望这足够清楚吗?
const ID = ''//Your access key id
const SECRET = ''//Your AWS secret access key
const BUCKET_NAME = ''//Put your bucket name here
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
})
const params = {
Bucket: BUCKET_NAME,
CreateBucketConfiguration: {
// Set your region here
LocationConstraint: "eu-west-1"
}
}
s3.createBucket(params, function(err, data) {
if (err && err.statusCode == 409){
console.log("Bucket has been created already");
}else{
console.log('Bucket Created Successfully', data.Location)
}
})