Access Files from AWS S3 Bucket Using NodeJs
Tags: aws, tutorial, node, javascript
Published: 2022-07-16 09:19:53

**Here we will learn how to _upload_ , _download_ and _delete_
files in AWS S3 bucket using NodeJs**

## Step 1: Create a AWS account 

- First we need to create a AWS account if we don't have one

- You may create a free tier account but you need to fill your card details there

## Step 2: Initialize the Project

- Create a folder lets say 's3' in your desktop or wherever you
want 

- Open the terminal and direct their using cd command
       - cd desktop
       - cd s3

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5959ybx4amk7fts3nqo7.png)
- Now add npm json file in it
       - npm init -y

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhpwsmi2rz4welyhj8uu.png)

- create a file 'app.js' in the folder s3 

## Step 3: Installing the required dependencies

- Install express, aws-sdk and multer in your folder i.e. s3
       - npm install express aws-sdk multer multer-s3 
 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2jt9451u2lxq9cwiehj.png)

## Step 4: S3 bucket setup

- Open the **AWS** console 

- Now Search S3 there and then open S3

- Click on Create bucket option

- Set name and region there and unselect☑️ 'block all public access'

- select✅ 'Block public access to buckets and objects granted through new public bucket or access point policies' 
and 'Block public and cross-account access to buckets and objects through any public bucket or access point policies'

- Click on create bucket

**congratulations your bucket is created**

## Step 5: Create AWS Credentials

- First click on 'Innominds'

- Then click on 'My security credentials'

- Then click on the 'Access key' and then 'Create New Access Key'

- You will get your access key there

## Step 6: Create .env file

- Create a .env file in your s3 folder

- Inside .env file enter:-
       - ACCESS_KEY = (your access key)
       - ACCESS_SECRET = (your secret access key)
       - REGION = (region of your bucket)
       - BUCKET = (name of your bucket)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mllnom421squdtx9fmta.png)


## Step 7: Create a express server

- create express server inside the file 'app.js'

- Don't forget to add .env file to your 's3' folder
       -npm i dotenv

- Declare all the previously mentioned libraries like aws-sdk, multer, multer-s3 in your express server

## Step 8: Use muller with aws-sdk to acccess the file

## Here is one standard Example for Express server:-

require("dotenv").config()

const express = require('express')

const app = express();

app.listen(3001);

const aws = require('aws-sdk')
const multer = require('multer')
const multerS3 = require('multer-s3');


aws.config.update({
    secretAccessKey: process.env.ACCESS_SECRET,
    accessKeyId: process.env.ACCESS_KEY,
    region: process.env.REGION,

});
const BUCKET = process.env.BUCKET
const s3 = new aws.S3();

const upload = multer({
    storage: multerS3({
        s3: s3,
        acl: "public-read",
        bucket: BUCKET,
        key: function (req, file, cb) {
            console.log(file);
            cb(null, file.originalname)
        }
    })
})

app.post('/upload', upload.single('file'), async function (req, res, next) {

    res.send('Successfully uploaded ' + req.file.location + ' location!')

})

app.get("/list", async (req, res) => {

    let r = await s3.listObjectsV2({ Bucket: BUCKET }).promise();
    let x = r.Contents.map(item => item.Key);
    res.send(x)
})


app.get("/download/:filename", async (req, res) => {
    const filename = req.params.filename
    let x = await s3.getObject({ Bucket: BUCKET, Key: filename }).promise();
    res.send(x.Body)
})

app.delete("/delete/:filename", async (req, res) => {
    const filename = req.params.filename
    await s3.deleteObject({ Bucket: BUCKET, Key: filename }).promise();
    res.send("File Deleted Successfully")

})