In this article, I will explain how to download file from Node.js server using express framework. I am explaining here for express framework since its one of the most popular nodejs framework. And with express its very easy to download file from Node.js server, Since express framework provides helper function.
res.download(path [, filename] [, fn])
;
This function, transfers the file at path as an attacchement. Browser will prompt the user for download. And when an error occurs or transfer is complete, the method calls the optional callback function fn. This method uses res.sendFile()
to transfer the file.
Create a new app by typing below commands over terminals
mkdir nodejs-app
cd nodejs-app
npm init --yes
npm i - express
Once all command run successfully, Then we will create the main file named server.js in the project folder. So create the file and put below code inside that file.
In the above file, We have created a simple app which has a route to download the file.
Now run the app with command node server.js . And put the link http://localhost:3000/download/your-file-name, add the filename at the end of the url.A download prompt will show
Download file from Node.js server is easy, We don't need to do much stuff here.
That’s all for now. Thank you for reading and I hope this article will be very helpful to understand file download from Node.js server.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.