expressjsHow do I download a file using Express.js?
To download a file using Express.js, you can use the res.download
method. This method takes the path of the file as an argument and streams the file to the response object.
For example:
app.get('/download', (req, res) => {
const file = `${__dirname}/public/file.pdf`;
res.download(file);
});
This code will send the file located at /public/file.pdf
to the response object.
Code explanation
-
app.get('/download', (req, res) => {
: This is the route definition. It defines the request URL and the callback function that will be called when the URL is requested. -
const file =
${__dirname}/public/file.pdf;
: This defines the path of the file to be downloaded. -
res.download(file);
: This is the method that sends the file to the response object.
Here are some ## Helpful links
More of Expressjs
- How can I use express-zip js to zip and download files?
- How do I find Express.js tutorials on YouTube?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Express.js to parse YAML files?
- How can I set up unit testing for an Express.js application?
- How do I use Express.js to make an options request?
- How do I implement CSRF protection in an Express.js application?
- How can I disable the X-Powered-By header in Express.js?
- How do I download a zip file using Express.js?
- How do I use Zod with Express.js?
See more codes...