Open In App

How to download a file using Express.js ?

Last Updated : 17 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. 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.
  2. 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 routing
const express = require('express')
 
// Creating app
const app = express();
 
// Requiring express-zip for downloading a zip file
const zip = require('express-zip');
 
// The folder path for the files
const folderPath = __dirname+'/Files';
 
// GET request for single file
app.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 zip
app.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 app
app.get('/', function(req, res){
    res.sendFile(__dirname+'/index.html');
})
 
// Creating server at port 3000
app.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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads