In this blog post, we will explore how to send files using Express, a popular framework for building web applications in Node.js. We will focus on the Response.download() method, which allows you to transfer files as attachments.

When a user visits a route that uses the Response.download() method, their browser will prompt them to download the file instead of displaying it in the browser window. This is useful when you want to send files, such as PDFs or images, to your users.

To send a file using Response.download(), you first need to set up an Express route. Here’s an example:

app.get('/', (req, res) => res.download('./file.pdf'));

In this example, when a user visits the root route of your application, Express will send the file.pdf file as an attachment. The file will be downloaded to the user’s device.

You can also specify a custom filename for the downloaded file. Here’s how you can do it:

res.download('./file.pdf', 'user-facing-filename.pdf');

With this modification, the downloaded file will have the name user-facing-filename.pdf, regardless of the original filename.

Additionally, the Response.download() method provides a callback function that can be used to execute code once the file has been sent. This can be useful for handling errors or performing additional actions. Here’s an example:

res.download('./file.pdf', 'user-facing-filename.pdf', (err) => {
  if (err) {
    // Handle error
    return;
  } else {
    // Do something
  }
});

In this example, if an error occurs while sending the file, it will be handled in the callback function. Otherwise, you can perform additional actions once the file transfer is complete.

By following these steps, you can easily send files using Express and the Response.download() method. This feature allows you to provide a seamless file download experience for your users.