As I continue expanding on express.js this month today I thought I would write about the response download method, which is one of the many methods in express that are part of the standard response object that I might write about more this week. The download response method will send a file as an attachment rather than the content to be displayed, so it does differ a little from the send file response method that would be used as a way to send a file as browser display content, rather than an attachment to be downloaded to a place on a clients local file system.
This download method of the response object of a middleware function is useful if you want to have some kind of path that will work as a way to deliver a file as a download when a link is clicked, or something to that effect. When doing so the user should end up being prompted if they want to download the file, and if it is something they want they can then click to downloaded to a location on there local file system. It is very easy to use, you do not have to worry about setting the proper headers or anything like that it does it all for you so all that has to be done basically is to just call a method in the response object.
Also in this post I am working with express.sj version 4.16.3, which as of this writing is the latest version.
For a basic example I have just a single file called doc1.txt in a folder called docs in the root of my demo folder. For this demo the only dependency that is needed is express itself.
Now I just need to start the app in the command line by calling the script with node.
And go to localhost:8080 in my browser I see the get a doc link, when I click it I end up downloading doc1.txt to the downloads folder. So then the app seems to work as expected the res download method in express can be used to start a download of a file for a user that goes to a given path. this of course can prove to be a useful feature for all kinds of applications that call for such an action.
The response download method works great if you want something to be treated as a file download. this makes the method useful for things like documents and platform dependent binaries that are meant to be used outside of the browser in some capacity. There are many other such methods like res.sendFile that can also be used to just send a file to the client, although they do work differently. If you want to just host some files in a public folder of sorts you would want to use express.static. If you enjoyed this post consider reading my other posts on express.