0
0
ExpressHow-ToBeginner · 3 min read

How to Send File in Express: Simple Guide with Examples

In Express, you can send a file to the client using res.sendFile(filePath). This method streams the file from the server to the browser, allowing users to download or view it directly.
📐

Syntax

The basic syntax to send a file in Express is:

  • res.sendFile(path [, options] [, callback])

Here, path is the absolute path to the file you want to send. options is optional and can include settings like root directory. callback runs after the file is sent or if an error occurs.

javascript
res.sendFile(path, options, callback)
💻

Example

This example shows how to send a file named example.pdf located in a folder called public when the user visits /download.

javascript
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

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

app.get('/download', (req, res) => {
  const filePath = path.join(__dirname, 'public', 'example.pdf');
  res.sendFile(filePath, (err) => {
    if (err) {
      res.status(404).send('File not found');
    }
  });
});

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 starts downloading or displaying example.pdf.
⚠️

Common Pitfalls

Common mistakes when sending files in Express include:

  • Using a relative path instead of an absolute path, which causes errors.
  • Not handling errors in the callback, so the user gets no feedback if the file is missing.
  • Forgetting to set correct permissions on the file or folder, preventing access.

Always use path.join with __dirname to build absolute paths and handle errors gracefully.

javascript
/* Wrong way: Using relative path without __dirname */
app.get('/file', (req, res) => {
  res.sendFile('public/example.pdf'); // This will cause an error
});

/* Right way: Using absolute path */
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

app.get('/file', (req, res) => {
  const filePath = path.join(__dirname, 'public', 'example.pdf');
  res.sendFile(filePath, (err) => {
    if (err) {
      res.status(404).send('File not found');
    }
  });
});
📊

Quick Reference

  • res.sendFile(path): Sends the file at the given absolute path.
  • path.join(...paths): Safely builds file paths.
  • __dirname: Current directory of the running script, used to build absolute paths.
  • Always handle errors in the callback to inform users if the file is missing.

Key Takeaways

Use res.sendFile with an absolute file path to send files in Express.
Build file paths safely using path.join and __dirname to avoid errors.
Always handle errors in the sendFile callback to provide user feedback.
Ensure the file and folder permissions allow Express to access the file.
res.sendFile streams the file efficiently, letting browsers download or display it.