s3 list objects in folder node js
To list objects in a folder in Node.js using the AWS SDK for JavaScript, you can follow the steps below:
- Import the AWS SDK: Begin by importing the AWS SDK for JavaScript into your Node.js application. You can do this by requiring the
aws-sdk
package:
const AWS = require('aws-sdk');
- Configure the AWS SDK: Next, you need to configure the AWS SDK with your AWS credentials. You can do this by creating a new instance of the
AWS.S3
class and passing in your credentials:
const s3 = new AWS.S3({
accessKeyId: 'YOUR_ACCESS_KEY',
secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
region: 'us-west-2' // Replace with your desired AWS region
});
Make sure to replace 'YOUR_ACCESS_KEY'
and 'YOUR_SECRET_ACCESS_KEY'
with your actual AWS access key and secret access key.
- List objects in the folder: To list objects in a specific folder, you can use the
listObjectsV2
method of thes3
object. Pass in the name of the bucket and the prefix of the folder you want to list objects from:
const listParams = {
Bucket: 'YOUR_BUCKET_NAME',
Prefix: 'folder_name/'
};
s3.listObjectsV2(listParams, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data.Contents);
}
});
Replace 'YOUR_BUCKET_NAME'
with the name of your AWS S3 bucket and 'folder_name/'
with the prefix of the folder you want to list objects from.
- Handle the response: The
listObjectsV2
method will return a response with the list of objects in the specified folder. You can access the list of objects in theContents
property of the response data.
Note: Remember to handle any errors that may occur during the API call.
That's it! By following these steps, you will be able to list objects within a specific folder in AWS S3 using Node.js.