6

I am trying to read a JSON file stored in an S3 bucket. I am trying to get the JSON file contents using getObject command of Javascript SDK. I am getting output as [object Object] when I convert the aws response to utf8 string. This is my nodeJS code:

const s3Client = require("./aws_s3_connect");
const { GetObjectCommand } = require("@aws-sdk/client-s3");
//const storage_file_path = "";

const run = async (input_data) => {

    const bucket_name = "bucket_name";
    const file_path = "";
    const file_name = "sample.json";

    const bucketParams = {
        Bucket: bucket_name,
        Key: file_path + file_name,
        ResponseContentType: 'application/json'
    };

    try {
        // Send get object command
        let aws_response = await s3Client.send(new GetObjectCommand(bucketParams));
        console.log(aws_response);
        //var blob = new Blob(aws_response.Body);
        let data = aws_response.Body.toString('utf8');
        console.log(data);

        return data;
    } catch (err) {
        console.log("Error", err);
    }
};

module.exports = { run };

Please help me to identify the issue. Thanks for your help.

2

1 Answer 1

5

Working example

FROM 22/08/2023 you can use the built-in function transformToString

And assuming you have a bucket and a file/object ready

import { S3Client, GetObjectCommand} from '@aws-sdk/client-s3';
const s3 = new S3Client({region: "eu-west-1"});

const params = {Bucket: "my-unique-bucket", Key: "my-s3-object"};
const res = await s3.send(new GetObjectCommand(params));
const bodyString = await res.Body.transformToString();

Reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_GetObject_section.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.