Read json file from S3 using V3 AWS SDK
Thanks to this blog: https://blog.salvatorecozzubo.com/read-files-from-amazon-s3-using-node-js-f89be033ba12
import {
S3Client,
GetObjectCommand,
PutObjectCommand
} from "@aws-sdk/client-s3";
import { v4 as uuidv4 } from 'uuid';
const s3Client = new S3Client({ region: 'put your region'});
const bucket = 'put your bucket name';
const key = 'put your key name'; // you can copy it from the S3 console
export class S3{
constructor() {
this.getObject = this.getObject.bind(this);
this.putItem = this.putItem.bind(this);
}
async getObject(input) {
const streamToString = (stream) => new Promise((resolve, reject) => {
const chunks = [];
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('error', reject);
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
});
const params = {
"Bucket": bucket,
"Key": key,
}
const command = new GetObjectCommand(params);
try {
let response:any = await s3Client.send(command);
const { Body } = response;
let result: string = await streamToString(Body) as string;
result = JSON.parse(result);
return result;
} catch (error) {
console.log(error);
throw error;
}
}
async putItem(body) {
const objBuffer = Buffer.from(JSON.stringify(body));
const params = {
"Bucket": bucket,
"Key": key,
"Body": objBuffer,
"ContentType": 'application/json',
}
const command = new PutObjectCommand(params);
try {
const response = await s3Client.send(command);
return response;
} catch (error) {
console.log(error);
}
}
}