Read json file from S3 using V3 AWS SDK

Arun Rajeevan
N-OMS Tech Radar
Published in
1 min readDec 24, 2022

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);
}
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in N-OMS Tech Radar

This publication focuses on cloud technologies, application development, software architectures, best practices, the latest advancements in web technologies, and best engineering practices.

No responses yet

What are your thoughts?