9951 explained code solutions for 126 technologies


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

Edit this code on GitHub