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.