I am trying to read a JSON file stored in an S3 bucket. I am trying to get the JSON file contents using getObject mand 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 mand
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.
I am trying to read a JSON file stored in an S3 bucket. I am trying to get the JSON file contents using getObject mand 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 mand
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.
Share Improve this question asked Mar 8, 2023 at 11:44 Prithivin LakshminarayananPrithivin Lakshminarayanan 2173 silver badges12 bronze badges 2- 3 Does this answer your question? How to get response from S3 getObject in Node.js? – fedonev Commented Mar 8, 2023 at 12:15
- Thanks. I am able to read the json using the response you shared. – Prithivin Lakshminarayanan Commented Mar 8, 2023 at 12:30
1 Answer
Reset to default 4Working 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./AmazonS3/latest/userguide/example_s3_GetObject_section.html