Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Express provides a handy method to transfer a file as attachment: Response.download()
.
Once a user hits a route that sends a file using this method, browsers will prompt the user for download.
The Response.download()
method allows you to send a file attached to the request, and the browser instead of showing it in the page, it will save it to disk.
app.get('/', (req, res) => res.download('./file.pdf'))
In the context of an app:
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 filename:
res.download('./file.pdf', 'user-facing-filename.pdf')
This method provides a callback function which you can use to execute code once the file has been sent:
res.download('./file.pdf', 'user-facing-filename.pdf', (err) => {
if (err) {
//handle error
return
} else {
//do something
}
})
Download my free Express.js Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More express tutorials:
- Express, a popular Node.js Framework
- Retrieve the GET query string parameters using Express
- Validating input in Express using express-validator
- Express Templates
- Serving Static Assets with Express
- Send a JSON response using Express
- Express Sessions
- Send a response using Express
- Send files using Express
- Sanitizing input in Express using express-validator
- Routing in Express
- An Express HTTPS server with a self-signed certificate
- Express, Request Parameters
- Retrieve the POST query parameters using Express
- Handling redirects with Express
- Express Middleware
- Setup Let's Encrypt for Express
- Work with HTTP headers in Express
- Handling forms in Express
- Handling file uploads in forms using Express
- Handling CORS in Express
- Manage Cookies with Express