Sling Academy
Home/Node.js/How to Download a File from NodeJS Server using Express

How to Download a File from NodeJS Server using Express

Last updated: December 28, 2023

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!

Next Article: Express.js: The Difference Between app.use() and app.get()

Previous Article: How to Set Custom Status Codes in Express.js

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates