0
0
ExpressHow-ToBeginner · 3 min read

How to Download File in Express: Simple Guide

In Express, you can download a file by using the res.download() method, which sends the file as an HTTP response prompting the browser to download it. You provide the file path as the first argument, and optionally a filename and a callback for error handling.
📐

Syntax

The res.download() method sends a file to the client and prompts a download dialog in the browser.

  • filePath: The path to the file you want to send.
  • filename (optional): The name the file will have when downloaded.
  • callback (optional): A function to handle errors or perform actions after sending.
javascript
res.download(filePath, [filename], [callback])
💻

Example

This example shows a simple Express server that lets users download a file named example.txt located in the project folder when they visit /download.

javascript
import express from 'express';
import path from 'path';

const app = express();
const PORT = 3000;

app.get('/download', (req, res) => {
  const filePath = path.join(process.cwd(), 'example.txt');
  res.download(filePath, 'downloaded-example.txt', (err) => {
    if (err) {
      res.status(500).send('Error downloading file');
    }
  });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
Output
Server running on http://localhost:3000 When visiting http://localhost:3000/download, the browser prompts to download 'downloaded-example.txt'.
⚠️

Common Pitfalls

Common mistakes when using res.download() include:

  • Providing an incorrect file path, causing a 404 or error.
  • Not handling errors in the callback, which can leave the client hanging.
  • Forgetting to set correct file permissions so the server can read the file.

Always verify the file exists and handle errors gracefully.

javascript
import express from 'express';
import path from 'path';

const app = express();

// Wrong: No error handling and wrong path
app.get('/bad-download', (req, res) => {
  res.download('wrong/path/file.txt');
});

// Right: Correct path and error handling
app.get('/good-download', (req, res) => {
  const filePath = path.join(process.cwd(), 'file.txt');
  res.download(filePath, (err) => {
    if (err) {
      res.status(404).send('File not found');
    }
  });
});
📊

Quick Reference

Tips for using res.download():

  • Use path.join() to build file paths safely.
  • Always handle errors in the callback to avoid server crashes.
  • Set correct file permissions so Express can access the file.
  • Use descriptive filenames for better user experience.

Key Takeaways

Use res.download() to send files and prompt browser downloads in Express.
Always provide the correct file path and handle errors in the callback.
Use path.join() to safely create file paths.
Ensure the server has permission to read the file before sending.
Set a clear filename to improve the download experience.