How to use the AWS SDK for JavaScript with B2

 

B2 can easily be configured for use with the AWS SDK for JavaScript thanks to the S3 Compatible API. Below is an example of a sample.js that has been configured to set credentials, create a bucket, and upload a file.

  

/*
* Copyright 2013. Amazon Web Services, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

// Create an S3 client
var credentials = new AWS.SharedIniFileCredentials({profile: 'b2'});
AWS.config.credentials = credentials;
var ep = new AWS.Endpoint('s3.us-west-002.backblaze.com');
var s3 = new AWS.S3({endpoint: ep});

// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid.v4();
var keyName = 'hello_world.txt';

s3.createBucket({Bucket: bucketName}, function() {
var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else
console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
});
});

 

Content of the config.json

b2@vm:~/aws-nodejs-sample$ more config.json
{"accessKeyId": your_b2_keyid, "secretAccessKey": your_appKey, "region": "us-west-002" }

 

You can also have the credentials added to the ~/.aws/credentials as a separate profile

 [b2]
aws_access_key_id = your_b2_keyId
aws_secret_access_key = your_b2_appKey

 

In this case, you won’t need the following 2 lines in the script above 

var credentials = new AWS.SharedIniFileCredentials({profile: 'b2'});
AWS.config.credentials = credentials;

Then run the same script as follows.

  b2@vm:~/aws-nodejs-sample$ AWS_PROFILE=b2 node sample.js
Successfully uploaded data to node-sdk-sample-38cb5413-29c2-46f5-ab2d-4ac4d553f929/hello_world.txt

The S3 Compatible API for Backblaze B2 Cloud Storage allows 1000’s of integrations to work with B2 natively. If you’re new to the S3 Compatible API, please see our Getting Started Guide. If you have any trouble using AWS SDK for JavaScript with B2, please let us know by emailing us at b2feedback@backblaze.com.

 

Have more questions? Submit a request

0 Comments

Article is closed for comments.
Powered by Zendesk