Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to download files using Express.js

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.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments