In this tutorial, you will learn how to download files from the server in node js + express using using `res.download()` methods.
How to Download File From Rest API in Node js Express
Steps to download files to client from server:
Step 1 – Create Node Express js App
Run the following command on cmd to create node js app:
mkdir my-app cd my-app npm init
Step 2 – Install Node Modules
Run the following command on cmd to install express dependencies:
npm install express --save
Step 3 – Create Server.js File
Create a Server.js file, and import above installed modules in it:
const express = require('express'); const app = express(); const path = require('path');
Step 4 – Create Routes
Create routes in server.js file to handle download file logic:
//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); });
Step 5 – Test Application
Run the following command on cmd to start node express js server:
//run the below command npm start
To download files in node js server:
API URL :- http://localhost:3000/download/your-file-name Method :- GET
Conclusion
Node js + express rest API download file; Through this tutorial, you have learned how to download files from server in node js + express+ rest API.
The article provides a step by step information for Node js Rest API Download. So I follow these steps and easily download them on my system. Thank you for sharing this information.
nice