
This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using NodeJS. If not, check out my article Getting Started with NodeJS aws-sdk.
The @aws-sdk/client-s3 package is used to interact with AWS S3 Buckets in NodeJS. The npm list command can be used to determine if you have the @aws-sdk/client-s3 package installed. If not, the npm install command can be used to install the @aws-sdk/client-s3 package. Once installed, your package.json should include the @aws-sdk/client-s3 package.
{
"dependencies": {
"@aws-sdk/client-s3": "^3.600.0"
}
}
Here is the minimal boilerplate code without any error handling to list your S3 Buckets using CommonJS.
const { S3Client, ListBucketsCommand } = require("@aws-sdk/client-s3");
const client = new S3Client({ region: "us-east-1" });
async function getS3Buckets() {
const params = {};
const command = new ListBucketsCommand(params);
return await client.send(command);
}
getS3Buckets()
.then(
response => {
//response is really only needed for testing/debugging purposes, to see the full response
//console.log(response)
console.log(response.Buckets);
}
)
.catch(
err => {
console.error(err)
process.exit(1)
}
)
If your app is an ES module, package.json will have "type": "module".
{
"type":"module",
"dependencies": {
"@aws-sdk/client-s3": "^3.600.0"
}
}
In this scenario, you will use import instead of require.
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";
Which should return something like this.
{
'$metadata': {
httpStatusCode: 200,
requestId: 'WPVKXTADSVVF4VSW',
extendedRequestId: 'OdGZ9obEUzuAIRYn75N4JmRhi+wL6UuBv9kMos90MCX7WYbeA0BHHT5jCfZhxR5jrHZIPavDqlg=',
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
Buckets: [
{
Name: 'foo-bucket',
CreationDate: 2024-04-19T01:38:37.000Z
},
{
Name: 'bar-bucket',
CreationDate: 2023-07-21T23:17:02.000Z
}
],
Owner: {
DisplayName: 'john.doe',
ID: 'ab0e0a41e318d5103a77c822adsfadsfadfacc325c65b5c777a5f8e743743'
}
}
You probably just want the name of the S3 Bucket.
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";
const client = new S3Client({ region: "us-east-1" });
async function getS3Buckets() {
const params = {};
const command = new ListBucketsCommand(params);
return await client.send(command);
}
getS3Buckets()
.then(
response => {
//response is really only needed for testing/debugging purposes, to see the full response
//console.log(response)
response.Buckets.forEach(item => {
console.log(item.Name)
})
}
)
.catch(
err => {
console.error(err)
process.exit(1)
}
)
Did you find this article helpful?
If so, consider buying me a coffee over at