Installation
@aws-sdk/client-s3
npm install @aws-sdk/client-s3Initialize Client
JavaScript Example
import { S3Client } from "@aws-sdk/client-s3";
const s3Client = new S3Client({
endpoint: "http://your-server-ip:3000",
region: "us-east-1",
credentials: {
accessKeyId: "YOUR_ACCESS_KEY",
secretAccessKey: "YOUR_SECRET_KEY",
},
forcePathStyle: true, // Required for V2 Capsule
});Common Operations
Upload a File
import { PutObjectCommand } from "@aws-sdk/client-s3";
import fs from "fs";
const fileContent = fs.readFileSync("myfile.txt");
const command = new PutObjectCommand({
Bucket: "my-bucket",
Key: "myfile.txt",
Body: fileContent,
});
await s3Client.send(command);Download a File
import { GetObjectCommand } from "@aws-sdk/client-s3";
const command = new GetObjectCommand({
Bucket: "my-bucket",
Key: "myfile.txt",
});
const response = await s3Client.send(command);
const content = await response.Body.transformToString();List Objects
import { ListObjectsV2Command } from "@aws-sdk/client-s3";
const command = new ListObjectsV2Command({
Bucket: "my-bucket",
});
const response = await s3Client.send(command);
response.Contents.forEach((obj) => {
console.log(obj.Key - obj.Size bytes);
});Delete a File
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
const command = new DeleteObjectCommand({
Bucket: "my-bucket",
Key: "myfile.txt",
});
await s3Client.send(command);