AWS SDK for JavaScript: Working with Amazon S3
Introduction
The AWS SDK for JavaScript provides a convenient way to interact with Amazon S3, a cloud storage service that offers easy-to-use object storage with a simple web service interface. This article will provide examples of how to use the AWS SDK for JavaScript to perform various actions and implement common scenarios with Amazon S3.
Creating a Bucket
To create a new S3 bucket, use the
createBucket
method. The following code example shows how to create a bucket named "my-bucket" in the "us-east-1" region: ``` const AWS = require('aws-sdk'); const s3 = new AWS.S3({region: 'us-east-1'}); s3.createBucket({Bucket: 'my-bucket'}, (err, data) => { if (err) { console.error(err); } else { console.log('Bucket created:', data.Location); } }); ```
Uploading an Object
To upload an object to an S3 bucket, use the
putObject
method. The following code example demonstrates how to upload a file named "my-file.txt" to the "my-bucket" bucket: ``` s3.putObject({ Bucket: 'my-bucket', Key: 'my-file.txt', Body: fs.createReadStream('my-file.txt') }, (err, data) => { if (err) { console.error(err); } else { console.log('Object uploaded:', data); } }); ```
Downloading an Object
To download an object from an S3 bucket, use the
getObject
method. The following code example shows how to download the "my-file.txt" object from the "my-bucket" bucket: ``` s3.getObject({ Bucket: 'my-bucket', Key: 'my-file.txt' }, (err, data) => { if (err) { console.error(err); } else { console.log('Object downloaded:', data); } }); ```
Listing Buckets
To list all the buckets in your AWS account, use the
listBuckets
method. The following code example demonstrates how to list all buckets: ``` s3.listBuckets((err, data) => { if (err) { console.error(err); } else { console.log('Buckets:', data.Buckets); } }); ``` These are just a few examples of the many actions you can perform with the AWS SDK for JavaScript. For more information, refer to the AWS SDK for JavaScript documentation.
Comments