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 disable the X-Powered-By header in Express.js?
- How do I use Zod with Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I implement CSRF protection in an Express.js application?
- How can I use express-zip js to zip and download files?
- How can I set up X-Frame-Options in ExpressJS?
- How do I create an Express.js logo?
- How can I use Express.js and Kafka together to create an application?
- How do I use adm-zip with Express.js?
- How do I use Express.js to parse YAML files?
See more codes...