File downloads using node.js and Express
In this article, we will quickly go through how to send files in the response in an Express JS application that can be downloaded and saved by the browser.
Express.js provides a method to send files in the response, so that it gets prompted by the browser and saved to the local disk.
Syntax
res.download(path [, filename] [, options] [, fn])
Sending file without changing the name
res.download("uploads/output.xlsx");
In this case, output.xlsx will be fetched from the uploads directory and will be sent in the response.
Sending the file with new name
By default, the Content-Disposition header “filename=” parameter is path which typically appears in the browser dialog. We can override this default with filename which will be filled in the file download dialog.
res.download("uploads/output.xlsx", "output_for_27th.xlsx");
Handling errors
res.download() method provides a callback to handle errors.
res.download("uploads/output.xlsx", "output_for_27th.xlsx", (err) => { if (err) { //handle error return } else { //success } });
Sending multiple files
Multiple files can be sent in the response but not individually. We need to pack all the files together as an archive and send it in the response.