Open In App

How to handle file downloads in Express JS ?

When using ExpressJS, handling file uploads involves receiving files from clients. On the other hand, file downloads refer to serving files to clients. For file uploads, we typically use libraries to handle the file processing. On the other hand, for file downloads, it is common to use NodeJS’s built-in module to read files and serve them to clients.

Handling File Downloads in ExpressJS:

npm install express

Example: Below is the example to handle file downloads in ExpressJS.






// server.js
 
const express = require('express');
const app = express();
 
// Serve static files from the 'public' directory
app.use(express.static('public'));
 
// Route to handle file download
app.get('/download',
    (req, res) => {
        const fileName = 'myapp.txt';
        const filePath =
            __dirname + '/public/' + fileName;
 
        // Send the file as an attachment
        res.download(filePath, fileName);
    });
 
// Start the server
const port = 3000;
app.listen(port,
    () => {
        console.log(
            `Server is running
            on http://localhost:${port}`
        );
    });

Start the server using the following command.

node server.js

Output:



Output

Article Tags :