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 do I use Express.js to parse YAML files?
- How do I use adm-zip with Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- How do I use an express.js query parser?
- How can I use Express.js to generate a zip response?
- How do I set the time zone in Express.js?
- How do I use Express.js to create a YouTube clone?
- How can I use express-zip js to zip and download files?
See more codes...