如果不存在,则创建S3存储桶 [英] Create S3 Bucket if None Exists

查看:95
本文介绍了如果不存在,则创建S3存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的node.js应用程序需要将文件上传到S3.大多数情况下,它将文件上传到现有存储桶中.但是有时,需要首先创建存储桶.有没有一种方法可以检查存储桶是否已经存在,如果不存在,请在启动上传之前创建该存储桶?这是到目前为止我得到的:

My node.js application needs to upload files to S3. Most of the time, it will upload the file to an existing bucket. But sometimes, the bucket will need to be created first. Is there a way to check whether the bucket already exists, and if not, create it before initiating the upload? Here's what I've got so far:

function uploadit () {
  'use strict';
  console.log('Preparing to upload the verse.')
  var s3 = new AWS.S3({apiVersion: '2006-03-01'});
  var uploadParams = {Bucket: 'DynamicBucketName', key: '/test.mp3', Body: myvalue, ACL: 'public-read'};
  var file = 'MyVerse.mp3';

  var fs = require('fs');
  var fileStream = fs.createReadStream(file);
  fileStream.on('error', function(err) {
    console.log('File Error', err);
  });
  uploadParams.Body = fileStream;

  var path = require('path');
  uploadParams.Key = book.replace(/ /g, "")+reference.replace(/ /g, "")+"_user"+userid+".mp3";

  // call S3 to retrieve upload file to specified bucket
  s3.upload (uploadParams, function (err, data) {
    if (err) {
      console.log("Error", err);
    } if (data) {
      console.log("Upload Success", data.Location);
      linkit();
      addanother();
    }
  });

}

推荐答案

waitFor should be able to get you whether if a bucket does not exist.

var params = {
  Bucket: 'STRING_VALUE' /* required */
};
s3.waitFor('bucketNotExists', params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

如果存储桶不存在,则可以创建它.

If a bucket does not exist, then you can create it.

希望有帮助.

这篇关于如果不存在,则创建S3存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆