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:
Import the AWS SDK module by requiring it:
const AWS = require('aws-sdk');
Create a new instance of the S3 class:
const s3 = new AWS.S3();
Define the parameters for the
getObject
method. In this example, we specify theBucket
andKey
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'
};
- Call the
getObject
method on thes3
object, passing in theparams
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);
}
});
- 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.