Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Express provides a handy method to send a file as an attachment: res.download().
When a user hits a route that sends a file using this method, the browser will prompt for download.
The res.download() method sends a file in the response; the browser will save it to disk instead of displaying it in the page.
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 accepts a callback function that runs after the file has been sent:
res.download('./file.pdf', 'user-facing-filename.pdf', (err) => {
if (err) {
//handle error
return
} else {
//do something
}
})