res.download()
Transfers a file as an attachment, prompting the browser to download it.
Syntax
res.download(path[, filename][, options][, callback]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Yes | The path of the file to send. |
filename | string | No | The name shown to the user in the download dialog. |
callback | function | No | `(err)` invoked after the transfer or on error. |
Returns
void — Streams the file; reports completion via callback.
Examples
app.get('/invoice/:id', (req, res) => {
res.download(`./invoices/${req.params.id}.pdf`, 'invoice.pdf');
});
Output
Content-Disposition: attachment; filename="invoice.pdf"
app.get('/file', (req, res) => {
res.download('./missing.txt', (err) => {
if (err && !res.headersSent) res.sendStatus(404);
});
});
Output
(404 Not Found)
Notes
Wraps `res.sendFile` plus the attachment header. Never build the
path from raw user input - validate or resolve against a fixed base
directory to prevent path traversal. Handle the callback error to
avoid an unhandled exception when the file is missing.