Using Amazon S3 Bucket with Node.js: A Step-by-Step Guide

Amazon S3 (Simple Storage Service) is a popular object storage service offered by Amazon Web Services (AWS) that allows you to store and retrieve any amount of data from anywhere on the web. In this guide, we will walk you through the process of integrating Amazon S3 Bucket with Node.js to handle file uploads and downloads.

Prerequisites

Before you begin, make sure you have the following:

  1. An AWS account with access to S3 services.
  2. Node.js and npm (Node Package Manager) are installed on your machine.

Step 1: Set Up AWS Credentials

To interact with AWS services, you’ll need to configure your AWS credentials on your development environment. You can do this by using the AWS CLI or by manually creating a ~/.aws/credentials file. Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your actual AWS access and secret keys.

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

Step 2: Create an S3 Bucket

Log in to your AWS console and navigate to the S3 service. Create a new bucket by clicking the “Create bucket” button. Follow the prompts to choose a unique bucket name and configure other settings.

Step 3: Set Up Your Node.js Project

Create a new Node.js project (or use an existing one) and install the AWS SDK using npm:

npm install aws-sdk

Step 4: Use AWS SDK to Interact with S3

Upload a File to S3

In your Node.js file, require the AWS SDK and create a new instance of the S3 service:

const AWS = require('aws-sdk');
const fs = require('fs');

// Configure AWS SDK
AWS.config.update({region: 'us-east-1'}); // Change to your desired region

const s3 = new AWS.S3();

// Define the parameters for the upload
const params = {
  Bucket: 'your-bucket-name',
  Key: 'example.jpg', // Name of the file in S3
  Body: fs.readFileSync('path/to/local/file.jpg') // Local file to upload
};

// Upload the file
s3.upload(params, (err, data) => {
  if (err) throw err;
  console.log('File uploaded successfully.', data.Location);
});

Download a File from S3

To download a file from S3, use the getObject method:

const params = {
  Bucket: 'your-bucket-name',
  Key: 'example.jpg' // Name of the file in S3
};

s3.getObject(params, (err, data) => {
  if (err) throw err;
  fs.writeFileSync('downloaded.jpg', data.Body);
  console.log('File downloaded successfully.');
});

Step 5: Test Your Code

Run your Node.js file using node your-file.js and ensure that the file is uploaded and downloaded successfully.

Congratulations! You’ve successfully used Node.js to interact with Amazon S3 Bucket. You can now build applications that utilize S3 for file storage and retrieval.

Remember to manage your AWS credentials and access permissions carefully to ensure the security of your S3 resources. Happy coding!

Don’t forget to check other posts on AWS 😉