Downloading a file is the process of transferring a file from a remote server to your local computer or device. Files can be downloaded from a variety of sources, including websites, email attachments, cloud storage services, and file sharing services.
In this tutorial, we will learn how to download a file from a REST API in Node.js Express. To download files from REST API in Node.js Express we follow these steps
Execute the following command on terminal to create node js app:
mkdir my-app
cd my-app
npm init
Execute the following command on terminal to install express dependencies:
npm install express --save
Create Server.js file and then follow the below steps:
Open server.js file and import above installed modules, as shown below:
const express = require('express');
const app = express();
const path = require('path');
Open server.js file and crate download file rest API routes in node js app, as shown below:
//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);
});
Execute the following command on terminal to start node express js server:
//run the below command
npm start
To download files using rest APIs in node js server; So open postman call above created rest api into your postman app:
API URL :- http://localhost:3000/download/your-file-name
Method :- GET
This tutorial, you have learned how to download files from server in Node js, Express, Rest API.
Thanks for reading !!!