How to Download a File from NodeJS Server using Express

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Node.js is a powerful platform for building network applications, and Express is a popular web framework for Node.js. Together, they can be used to serve and manage downloads of files of any type. In this tutorial, we’ll explore how to set up an Express server and implement routes that allow users to download files from a Node.js server.

Throughout this guide, we will start with the basics, such as setting up a simple Express server and serving static files. Then, we’ll move on to more advanced concepts, such as streaming large files, handling errors, setting content headers, and securing file downloads with authentication middleware.

Setting Up

First, let’s create a new Node.js project and install Express:

$ mkdir nodejs-file-download
$ cd nodejs-file-download
$ npm init -y
$ npm install express

Now, set up a basic Express server in a file named app.js:

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

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

Basic File Download

To allow users to download a specific file, you can use the res.download() method provided by Express:

const path = require('path');

app.get('/download', (req, res) => {
    const filePath = path.join(__dirname, 'files', 'example.pdf');
    res.download(filePath);
});

Place the ‘example.pdf’ file inside a directory named ‘files’ in your project root. When users visit http://localhost:3000/download, they will be prompted to download ‘example.pdf’.

Serving Static Files

Express also has the ability to serve static files using the express.static middleware. To serve all files in a directory:

app.use('/static', express.static('public'));

The ‘public’ directory will now be statically served at the ‘/static’ route. Users can download files directly if they know the URL.

Streaming Large Files

To efficiently serve larger files, you can use streaming to prevent loading the entire file into memory:

app.get('/stream', (req, res) => {
    const filePath = path.join(__dirname, 'files', 'large-video.mp4');
    res.setHeader('Content-Disposition', 'attachment; filename=download.mp4');
    const readStream = fs.createReadStream(filePath);
    readStream.pipe(res);
});

This route streams the ‘large-video.mp4’ file to the client as an attachment called ‘download.mp4’.

Handling Errors

When providing downloads, you should handle errors such as missing files or read errors:

app.get('/download', (req, res) => {
    const filePath = path.join(__dirname, 'files', 'example.pdf');

    res.download(filePath, (err) => {
        if (err) {
            if (!res.headersSent) {
                res.status(404).send('File not found');
            } else {
                // Handle the error during streaming
                readStream.destroy();
                res.end();
            }
        }
    });
});

Conclusion

In conclusion, Node.js and Express make it simple to set up file downloads on a web server. Whether you are dealing with static file serving or streaming large files to the client with proper error handling, these tools offer a robust solution. By following the examples provided in this tutorial, you’ll be able to implement file download functionality in your own Node.js web application.

Remember to always check and sanitize user inputs and consider using additional security measures like authentication and authorization when offering sensitive files for download. Happy coding!