How to Download File From Rest API in Node js

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

  • Step 1: Create Node Express js App
  • Step 2: Install Node Modules
  • Step 3: Create Server.js File
    • Import Installed Modules
    • Create REST API to Download File
  • Step 4: Start Node Express Js App Server
  • Step 5: Test Node js Rest Api File Download

Step 1: Create Node Express js App

Execute the following command on terminal to create node js app:

mkdir my-app
cd my-app
npm init

Step 2: Install Node Modules

Execute the following command on terminal to install express dependencies:

npm install express --save

Step 3: Create Server.js File

Create Server.js file and then follow the below steps:

Import Installed Modules

Open server.js file and import above installed modules, as shown below:

const express = require('express');
const app = express();
const path = require('path');

Create REST API to Download File

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);
});

Step 4: Start Node Express Js App Server

Execute the following command on terminal to start node express js server:

//run the below command

npm start

Step 5:Test Node js Rest Api File Download

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 !!!

#nodejs #express 

1.55 GEEK