res.download lets your server send files to users so they can save them on their device. It makes downloading files easy and automatic.
0
0
res.download for file downloads in Express
Introduction
When you want users to download a report or invoice from your website.
When providing a file like a PDF, image, or document for users to save.
When you need to let users download software or updates.
When sharing exported data files like CSV or JSON from your app.
When sending any file that should be saved instead of shown in the browser.
Syntax
Express
res.download(path, [filename], [options], [callback])
path is the file location on your server.
filename is optional and sets the name users see when saving.
Examples
Sends the file 'report.pdf' for download with its original name.
Express
res.download('/files/report.pdf');Sends the file but users see it named 'monthly-report.pdf'.
Express
res.download('/files/report.pdf', 'monthly-report.pdf');
Downloads 'image.png' and logs an error if something goes wrong.
Express
res.download('/files/image.png', (err) => { if (err) console.log('Download error:', err); });
Sample Program
This Express server has a route '/download' that sends the file 'sample.txt' from the 'public' folder. The file will be downloaded as 'example.txt'. If the file is missing, it sends an error message.
Express
import express from 'express'; const app = express(); app.get('/download', (req, res) => { const filePath = './public/sample.txt'; res.download(filePath, 'example.txt', (err) => { if (err) { res.status(500).send('Sorry, file not found.'); } }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Make sure the file path is correct and accessible by your server.
Use the callback to handle errors like missing files or permission issues.
res.download sets headers so browsers know to download, not display, the file.
Summary
res.download sends files to users for easy downloading.
You can rename the file for the user with an optional filename.
Always handle errors to improve user experience.