Sometimes, we want to let users download files within our Express app.
In this article, we’ll look at how to let users download files from Express apps.
res.download
One way to let users download a file from a Node.js server is to use the res.download
method available with Express.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/download', (req, res) => {
const file = `${__dirname}/download/foo.txt`;
res.download(file);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We just specify the path to the file with the file
string variable.
Then we pass that to the res.download
method to download the file.
__dirname
is the current working directory of the Express app.
Serve Files as Static Files
We can also use the express.static
middleware to serve a folder in our server as a static files folder.
To do this, we write:
const express = require('express')
const app = express()
const port = 3000
app.use('/download', express.static('download'))
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We call app.use
to use the Express static middleware.
The first argument is the path that the user uses to access the static folder’s content.
And the 2nd argument is the Express static middleware.
We create the middleware by calling express.static
with the folder path string.
Therefore, we serve the download
folder in our server as the static folder.
res.attachment
We can also return a file as a response in our route with the route.attachment
method.
It takes the same argument as the res.download
method.
It sets the Content-Disposition
response header to attachment
.
And it also sets the Content-Type
response header according to the file type being downloaded.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/download', (req, res) => {
const file = `${__dirname}/download/foo.txt`;
res.attachment(file).send();
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We call res.attachment
with send
to send the file download response to the user.
Conclusion
There’re several ways we can use to let users download files to user’s device via an Express endpoint.