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 find Express.js tutorials on YouTube?
- How do I use Express.js to parse YAML files?
- How can I use Express.js to make an XHR request?
- How can I parse XML data using Express.js?
- How can I use Express.js and Vite together for software development?
- How do I render a template using Express.js?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How do I use Express.js with W3Schools?
- How can I create a quiz using Express.js?
- How can I get the IP address of a GET request using Express.js?
See more codes...