Node JS Download File to Amazon AWS s3 Bucket

Node JS Download File to Amazon AWS s3 Bucket

Install and set up an aws-s3 module in the application that allows users to download files from the aws s3 bucket. In this tutorial, you will learn how to download files to an aws S3 bucket using node js + express + aws-s3.

How to download files from the S3 bucket using node js?

Steps to download the file to the amazon s3 bucket:

Step 1 – Create Node Express js App

Run the following command on cmd to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install express, aws-s3 dependencies

Run the following command on cmd to install express, aws-s3 dependencies:

npm install express aws-sdk --save

Step 3 – Create Server.js File

Create server.js file in application root directory, and add the following code to it:

var express = require('express');
var app = express();
var AWS = require('aws-sdk');
var fs = require('fs');
app.get('/download-file', function(req, res, next){
    // download the file via aws s3 here
    var fileKey = req.query['fileKey'];
    console.log('Trying to download file', fileKey);
    
    AWS.config.update(
      {
        accessKeyId: "....",
        secretAccessKey: "...",
        region: 'ap-southeast-1'
      }
    );
    var s3 = new AWS.S3();
    var options = {
        Bucket    : '/bucket-url',
        Key    : fileKey,
    };
    res.attachment(fileKey);
    var fileStream = s3.getObject(options).createReadStream();
    fileStream.pipe(res);
});
app.listen(3000, function () {
   console.log('express is online');
})

Step 4 – Test Application

Run the following command on cmd to start node express js server:

//run the below command

npm start

Conclusion

That’s it, you have learned how to download files to amazon s3 bucket using node js + express + aws-s3.

Recommended Node JS Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *