Files
test-repo/s3.js
2026-01-16 12:37:08 +05:30

74 lines
2.1 KiB
JavaScript

const { S3Client, PutObjectCommand, ListBucketsCommand, GetObjectCommand } = require('@aws-sdk/client-s3');
// const { fromIni } = require('@aws-sdk/credential-providers');
const minioClient = new S3Client({
endpoint: 'http://localhost:9000/test', // MinIO server URL
region: 'us-east-1', // Required but not used by MinIO
credentials: {
accessKeyId: 'minioadmin', // Default MinIO credentials
secretAccessKey: 'minioadmin'
},
forcePathStyle: true, // REQUIRED for MinIO
sslEnabled: false // Set to true if using HTTPS
});
// List all buckets
async function listBuckets() {
try {
const command = new ListBucketsCommand({});
const response = await minioClient.send(command);
console.log('Buckets:', response.Buckets);
return response.Buckets;
} catch (error) {
console.error('Error listing buckets:', error);
}
}
// Upload a file
async function uploadFile(bucketName, objectName, fileContent) {
try {
const command = new PutObjectCommand({
Bucket: bucketName,
Key: objectName,
Body: fileContent,
ContentType: 'text/plain'
});
const response = await minioClient.send(command);
console.log('File uploaded:', response);
return response;
} catch (error) {
console.error('Upload error:', error);
}
}
// Download a file
async function downloadFile(bucketName, objectName) {
try {
const command = new GetObjectCommand({
Bucket: bucketName,
Key: objectName
});
const response = await minioClient.send(command);
const content = await response.Body.transformToString();
console.log('File content:', content);
return content;
} catch (error) {
console.error('Download error:', error);
}
}
// Example usage
(async () => {
// Create a bucket first (you need to create buckets via console or CLI)
const buckets = await listBuckets();
// console.log('Available buckets:', buckets);
// Upload a file
await uploadFile('cap-web', 'textfiles/test2.txt', 'Hello MinIO from Node.js!');
// // Download the file
// await downloadFile('cap-web', 'test.txt');
})();