How To Download File From Node.js Server

    Apr 02, 2019       by Pankaj Kumar

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.

 

Get Started

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.

 

 
const express = require('express');
const app = express();
const path = require('path');
 
//route to download a file
app.get('/download/:file(*)',(req, res) => {
var file = req.params.file;
var fileLocation = path.join('./uploads',file);
console.log(fileLocation);
res.download(fileLocation, file);
});
 
app.listen(3000,() => {
console.log(`application is running at: http://localhost:3000`);
});
 

 

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 

 

 

Conclusion

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.

 


WHAT'S NEW

Find other similar Articles here: