Providing the ability to download a file from a web application is one of the common use cases of web application development. In this tutorial, you’ll learn about how to download file in express web app. The tutorial assumes the reader to have basic understanding of express web framework and JavaScript.

Getting Started With Express App

Let’s get started by creating an express web app. Create a project directory and initialize the node project.

mkdir DownloadFile
cd DownloadFile
npm init

Once the project has been initialized, install express framework into the project.

// install express framework
npm install --save express

Create a file called app.js and add the following code:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('How To Download File In Express Web App!'))

app.listen(port, () => console.log(`App listening on port ${port}!`))

Save the above changes and run the express web app.

// run the app
node app.js

You will have the application running at http://localhost:3000.

Download File In Express

I’ll start by creating a route to render HTML page in express.

/**
 * Route to render the index HTML page.
 */
app.get('/index', (req, res) => {
    res.sendFile('index.html', {root : __dirname})
})

Create a file called index.html inside the project directory. Here is the index.html file:

<html>
    <head>
    <title> Download File In Express</title>
    <script src="https://code.jquery.com/jquery-1.11.1.js">     </script>
    </head>
    <body>
    <h2>Click on the button to download file in express</h2>
    <button id="btn">Download</button>
    </body>
</html>

Create a file called API_helper.js where you’ll define the download method. The download_file method takes in HTTP download URL. Here is how the download_file method looks :

/*
** This method downloads the file
** from the URL specified in the 
** parameters 
*/ 
download_file : function(url) {
    return new Promise((resolve, reject) => {
        let file = fs.createWriteStream('./output.pdf');
        http.get(url, function(response) {
            response.on('data', function(chunk) {
                file.write(chunk)
            })
            response.on('end', function() {
                console.log('download file completed.')
                resolve(file)
            })
        })
    })
}

The download_file method returns a promise which is resolved once the file download has been completed. It makes use of the http module to make a GET request to the download URL. On data event of the response the file chunk gets written to the file stream. On end event of response the promise is resolved with the downloaded file.

Here is the API_helper.js file:

const http = require('http')
const fs = require('fs')

module.exports = {

    /*
    ** This method downloads the file
    ** from the URL specified in the 
    ** parameters 
    */ 
    download_file : function(url) {
        return new Promise((resolve, reject) => {
            let file = fs.createWriteStream('./output.pdf');
            http.get(url, function(response) {
                response.on('data', function(chunk) {
                    file.write(chunk)
                })
                response.on('end', function() {
                    console.log('download file completed.')
                    resolve('File download completed.')
                })
            })
        })
    }
}

Let’s create a route which will download the file using the download_file method. Here is how it looks :

/*
** Route to download the file from the specified URL  
*/
app.get('/download', (req, res) => {
    api_helper.download_file('http://www.peoplelikeus.org/piccies/codpaste/codpaste-teachingpack.pdf')
    .then(response => {
        res.send(response)
    })
    .catch(error => {
        res.send(error)
    })
    
})

Let’s add some jQuery code to index.html page to make a call to the /download route. Here is the index.html page :

<html>


    <title> Download file in Express </title>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>

      $(function(){
        $('#btn').click(function(){
            $.ajax({url: "/download", type: 'GET', success: function(result){
                
            }});
        })
      })

    </script>
    </head>
    <body>
        <h2> Hello World</h2>
        <button id="btn">Download</button>
    </body>
</html>

Save the above changes and restart the server. Point your browser to http://localhost:3000/index and click on the download button. You will have the file downloaded inside the project directory.

Wrapping It Up

In this tutorial, you learnt how to download file in express web app. In the next part of the tutorial, you’ll learn how to download the file on the client system with a file progress bar.

Do let us know your thoughts in the comments below.