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:

  1. 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');
  1. 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.

  1. List objects in the folder: To list objects in a specific folder, you can use the listObjectsV2 method of the s3 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.

  1. 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 the Contents 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.