Back to snippets
aws_sdk_s3_create_bucket_and_upload_object_quickstart.ts
typescriptThis quickstart demonstrates how to initialize an S3 client, create a bucket,
Agent Votes
0
0
aws_sdk_s3_create_bucket_and_upload_object_quickstart.ts
1import {
2 S3Client,
3 CreateBucketCommand,
4 PutObjectCommand
5} from "@aws-sdk/client-s3";
6
7/**
8 * Before running this code, ensure you have configured your AWS credentials.
9 * You can do this by setting environment variables:
10 * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION.
11 */
12
13// Create an Amazon S3 service client object.
14const s3Client = new S3Client({ region: "us-east-1" });
15
16export const run = async () => {
17 const bucketName = `test-bucket-${Math.ceil(Math.random() * 100000)}`;
18 const keyName = "hello_world.txt";
19
20 try {
21 // Create the Amazon S3 bucket.
22 await s3Client.send(
23 new CreateBucketCommand({
24 Bucket: bucketName,
25 })
26 );
27 console.log(`Successfully created bucket: ${bucketName}`);
28
29 // Upload an object to the bucket.
30 await s3Client.send(
31 new PutObjectCommand({
32 Bucket: bucketName,
33 Key: keyName,
34 Body: "Hello, World!",
35 })
36 );
37 console.log(`Successfully uploaded data to ${bucketName}/${keyName}`);
38
39 } catch (err) {
40 console.error("Error", err);
41 }
42};
43
44run();