s3.getobject nodejs example

The following code snippet demonstrates an example of how to use the s3.getObject method in Node.js:

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

const params = {
  Bucket: 'my-bucket',
  Key: 'my-file.txt'
};

s3.getObject(params, (err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});

Explanation for each step:

  1. Import the AWS SDK module by requiring it: const AWS = require('aws-sdk');

  2. Create a new instance of the S3 class: const s3 = new AWS.S3();

  3. Define the parameters for the getObject method. In this example, we specify the Bucket and Key values. Replace 'my-bucket' with the name of your S3 bucket, and 'my-file.txt' with the key of the object you want to retrieve:

const params = {
  Bucket: 'my-bucket',
  Key: 'my-file.txt'
};
  1. Call the getObject method on the s3 object, passing in the params object and a callback function. The callback function will be executed once the operation is complete and will receive two arguments: an error object (err) and the retrieved data object (data):
s3.getObject(params, (err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});
  1. Inside the callback function, we check if an error occurred. If there is an error, we log it to the console. Otherwise, we log the retrieved data object to the console. You can modify the code to handle the retrieved data according to your requirements.