res.download() transfers a file as an attachment, prompting the browser to download it.
Syntax
res.download(path [, filename] [, options] [, fn])
Example
const express = require("express");
const app = express();
const PORT = 4800;
app.get("/invoice", (req, res) => {
res.download("invoices/inv-1001.pdf", "MyInvoice.pdf");
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
The file at invoices/inv-1001.pdf gets downloaded by the client as MyInvoice.pdf.
Use cases
- Letting users download generated reports or invoices.
- Serving downloadable documents with a friendlier filename than the one on disk.
- Providing file downloads as part of an API or web app.