Created
July 13, 2024 17:26
-
-
Save airicbear/b095bfb6407807bbe61fa383ce5e2d4f to your computer and use it in GitHub Desktop.
Get started with AWS SDK for JavaScript v3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createInterface } from "readline/promises"; | |
import { | |
S3Client, | |
PutObjectCommand, | |
CreateBucketCommand, | |
DeleteObjectCommand, | |
DeleteBucketCommand, | |
paginateListObjectsV2, | |
GetObjectCommand, | |
} from "@aws-sdk/client-s3"; | |
export async function main() { | |
const s3Client = new S3Client({}); | |
const bucketName = `test-bucket-${Date.now()}`; | |
await s3Client.send( | |
new CreateBucketCommand({ | |
Bucket: bucketName, | |
}) | |
); | |
await s3Client.send( | |
new PutObjectCommand({ | |
Bucket: bucketName, | |
Key: "my-first-object.txt", | |
Body: "Hello JavaScript SDK!", | |
}) | |
); | |
const { Body } = await s3Client.send( | |
new GetObjectCommand({ | |
Bucket: bucketName, | |
Key: "my-first-object.txt", | |
}) | |
); | |
console.log(await Body.transformToString()); | |
const prompt = createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
}); | |
const result = await prompt.question("Empty and delete bucket (y/n) "); | |
prompt.close(); | |
if (result === "y") { | |
const paginator = paginateListObjectsV2( | |
{ client: s3Client }, | |
{ Bucket: bucketName } | |
); | |
for await (const page of paginator) { | |
const objects = page.Contents; | |
if (objects) { | |
for (const object of objects) { | |
await s3Client.send( | |
new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }) | |
); | |
} | |
} | |
} | |
await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName })); | |
} | |
} | |
import { fileURLToPath } from "url"; | |
if (process.argv[1] === fileURLToPath(import.meta.url)) { | |
main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment