Skip to content

How to download files using Express.js

Last updated on July 6, 2023

In Express.js, you can download a file from the server using the res.download() method. Here’s an example of how to implement file download functionality:

const express = require('express');
const app = express();
const path = require('path');

app.get('/download', (req, res) => {
  const filePath = 'path/to/file.txt'; // Replace with the actual file path

  res.download(filePath, (err) => {
    if (err) {
      // Handle the error
      console.error('Error downloading file:', err);
      res.status(500).send('Error downloading file');
    }
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the above example, we create an endpoint /download that triggers the file download. When a request is made to /download, the res.download() method is used to send the file to the client.

The first argument of res.download() is the file path on the server, and the second argument is an optional callback function that handles any errors that occur during the download process.

You should replace 'path/to/file.txt' with the actual path to your file. Make sure the file exists on the server and is accessible.

When the file is successfully downloaded, the browser will prompt the user to save the file with its original name.

Remember to adjust the code based on your specific file path and requirements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments