Read, Write and Delete file from S3 Bucket via NodeJS

Ankit Kumar Rajpoot
2 min readApr 28, 2020

--

Amazon simple storage service (Amazon S3) used as storage for the internet. It has a simple web services interface that helps developers to store and retrieve data from anywhere around the globe. It is a highly scalable, fast, inexpensive storage, reliable, and highly trusted database.

Configure AWS s3

Firstly you should have to install aws-sdk through the given command.

$ npm install aws-sdk

Then, configure the s3 through given code with IAM_USER_KEY , IAM_USER_SECRET , and BUCKET_NAME .

const s3 = new AWS.S3({
accessKeyId: IAM_USER_KEY, /* required */ # Put your iam user key
secretAccessKey: IAM_USER_SECRET, /* required */ # Put your iam user secret key
Bucket: BUCKET_NAME /* required */ # Put your bucket name
});

Parameters:

const params = {
Bucket: BUCKET_NAME, /* required */ # Put your bucket name
Key: fileName /* required */ # Put your file name
};

We have converted all functions into promises . You can use any function in promises or async/await.

Upload File

In this section, we will see how to upload a file from our machine to s3 bucket. Use the following code.

#This function for upload file to s3 bucketconst s3upload = function (params) {
return new Promise((resolve, reject) => {
s3.createBucket({
Bucket: BUCKET_NAME /* Put your bucket name */
}, function () {
s3.putObject(params, function (err, data) {
if (err) {
reject(err)
} else {
console.log("Successfully uploaded data to bucket");
resolve(data);
}
});
});
});
}

Read File

In this section, we will see how to read file data from s3 bucket. Use the following code.

# This function for read/download file from s3 bucketconst s3download = function (params) {
return new Promise((resolve, reject) => {
s3.createBucket({
Bucket: BUCKET_NAME /* Put your bucket name */
}, function () {
s3.getObject(params, function (err, data) {
if (err) {
reject(err);
} else {
console.log("Successfully dowloaded data from bucket");
resolve(data);
}
});
});
});
}

Delete File

In this section, we will see how to delete file data from s3 bucket. Use the following code.

# This function for delete file from s3 bucketconst s3delete = function (params) {
return new Promise((resolve, reject) => {
s3.createBucket({
Bucket: BUCKET_NAME /* Put your bucket name */
}, function () {
s3.deleteObject(params, function (err, data) {
if (err) console.log(err);
else
console.log(
"Successfully deleted file from bucket";
);
console.log(data);
});
});
});
};

An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services’ (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata.

--

--

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.