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 * This example demonstrates how to:
9 * 1. Create an S3 client.
10 * 2. Create a new S3 bucket.
11 * 3. Upload a simple text object to the new bucket.
12 */
13const run = async () => {
14 // Create an Amazon S3 service client object.
15 // The region is inferred from the local environment or configuration files.
16 const s3Client = new S3Client({ region: "us-east-1" });
17
18 const bucketName = `test-bucket-${Math.ceil(Math.random() * 100000)}`;
19 const keyName = "hello_world.txt";
20
21 try {
22 // 1. Create the Amazon S3 bucket.
23 console.log(`Creating bucket ${bucketName}...`);
24 await s3Client.send(
25 new CreateBucketCommand({
26 Bucket: bucketName,
27 })
28 );
29 console.log(`Successfully created bucket ${bucketName}`);
30
31 // 2. Put an object into the Amazon S3 bucket.
32 console.log(`Uploading object ${keyName} to ${bucketName}...`);
33 await s3Client.send(
34 new PutObjectCommand({
35 Bucket: bucketName,
36 Key: keyName,
37 Body: "Hello, World!",
38 })
39 );
40 console.log(`Successfully uploaded object ${keyName} to ${bucketName}`);
41
42 } catch (err) {
43 console.error("Error", err);
44 }
45};
46
47run();