Express provides a convenient way to transfer files as attachments:Response.download()
Express provides a convenient way to transfer files as attachments:Response.download()
.
Once the user clicks on the route that uses this method to send the file, the browser will prompt the user to download it.
ThisResponse.download()
The method allows you to send the file attached to the request and the browser will save it to disk instead of displaying it on the page.
app.get('/', (req, res) => res.download('./file.pdf'))
In the context of the application:
const express = require('express')
const app = express()
app.get(’/’, (req, res) => res.download(’./file.pdf’))
app.listen(3000, () => console.log(‘Server ready’))
You can set the file to be sent with a custom file name:
res.download('./file.pdf', 'user-facing-filename.pdf')
This method provides a callback function, once the file is sent, you can use the callback function to execute code:
res.download('./file.pdf', 'user-facing-filename.pdf', (err) => {
if (err) {
//handle error
return
} else {
//do something
}
})
Download mine for freeExpress.js manual
More crash tutorials:
- Express, the popular Node.js framework
- Use Express to retrieve GET query string parameters
- Use express-validator to validate input in Express
- Express template
- Use Express to serve static assets
- Send JSON response using Express
- Fast meeting
- Send a reply using Express
- Send files using Express
- Use Express-Validator to clean up the input in Express
- Route in Express
- Express HTTPS server with self-signed certificate
- Express, request parameters
- Use Express to retrieve POST query parameters
- Use Express to handle redirects
- Fast middleware
- Set up let's encrypt for Express
- Use HTTP headers in Express
- Processing forms in Express
- Use Express to process file uploads in forms
- Processing CORS in Express
- Use Express to manage cookies