By the end of this tutorial, you will be able to download files from the AWS S3 bucket using Express in NodeJS.
mkdir rabins-node-s3
cd rabins-node-s3
npm init -y
npm install express aws-sdk --save
nano server.js
Once you have created the server.js file you can add code as shown in the block below.
var express = require('express');
var app = express();
var express = require('express');
var AWS = require('aws-sdk');
var fs = require('fs');
const downloadFile = async (req, res, next) => {
var fileKey = req.query['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);
};
module.exports = {
downloadFile
};
// make sure to check the file location
const downloadController = require("download.controller");
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.get("/api/v1/products/", downloadController.downloadFile);
// setting the request query to download file via AWS S3 bucket
var fileKey = req.query['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);
});
Open your server.js file and add the following code to it:
var express = require('express');
var app = express();
require("download.routes")(app);
// You can specify port in your Node Environment or it will fire-up on 8080
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
npm run start