How to download a file using Express.js ? - GeeksforGeeks

17 Jan, 2022
Express.js  is a routing and middleware framework for handling the different routing of the webpage and it works between the request and response cycle and works on the top of the node.js server. In this article, we will discuss how to download a file using express.js.
To download a file using express.js we are going to see two scenarios:
Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs.Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name.
Downloading a single file using res.download() function which takes two parameters the path of the file and a function to handle if any error occurs.
Downloading multiple files as a zipped folder for this we would use the “express-zip” npm package which creates a zipped folder using the zip() function which takes an array of objects as a parameter. Each object has two fields path and file name.
Let’s first initialize the project and discuss each scenario one by one:
Step 1: create an “app.js” file and initialize your project with npm.
npm init
Step 2: Now install two npm packages: “express” and “express-zip“.
npm install express
npm install express-zip
Step 3: Create an “index.html” file and then create a folder named “Files” inside your project folder. In the files folder creates the below mentioned four text files:
single_gfg.txt
multiple_one_gfg.txt
multiple_two_gfg.txt
multiple_three_gfg.txt
The final project structure will look like this:
Project Structure
Step 4: Now let us code the “index.html” file. In it we will create two forms:
One with GET route as – ‘/single‘  (to handle the single file download request).
One with GET route as – ‘/multiple‘  (to handle the multiple file download request).
index.html 
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Download</title></head> <body>    <br>     <!-- Form to handle single file download request-->    <form action="/single" method="get">        <button type="submit">Download Single File</button>    </form>     <br><br>     <!-- Form to handle single file download request-->    <form action="/multiple" method="get">        <button type="submit">Download Multiple File</button>    </form></body> </html>
Step 5: Now code the “app.js” file. In it, we create GET request functions to handle the download requests using express. We use “express-zip” and res.download() as mentioned at the start.
app.js file
Javascript
// Requiring express package for routingconst express = require('express') // Creating appconst app = express(); // Requiring express-zip for downloading a zip fileconst zip = require('express-zip'); // The folder path for the filesconst folderPath = __dirname+'/Files'; // GET request for single fileapp.get('/single',function(req,res) {    console.log('single file');         // Download function provided by express    res.download(folderPath+'/single_gfg.txt', function(err) {        if(err) {            console.log(err);        }    })}) // GET request for multiple file download as zipapp.get('/multiple', function(req, res) {    console.log('Multiple file download')     // zip method which take file path    // and name as objects    res.zip([           { path: folderPath+'/multiple_one_gfg.txt',               name: 'one_gfg.txt'},           { path: folderPath+'/multiple_two_gfg.txt',               name: 'two_gfg.txt'},           { path: folderPath+'/multiple_three_gfg.txt',            name: 'three_gfg.txt'}    ])}) // GET request to the root of the appapp.get('/', function(req, res){    res.sendFile(__dirname+'/index.html');}) // Creating server at port 3000app.listen(3000,function(req,res){    console.log('Server started to listen at 3000');})
Step 5: Now run the app using your terminal.
node app.js
Output: Go to any browser and type http://localhost:3000
Output
You can go to the Downloads folder and extract the zip folder. So this is how we can download files using express in Node.js
rs1686740
simranarora5sos
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Node.js fs.readdirSync() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript