Node js Download File From Rest API

Node js Download File From Rest API

Node js + express rest API download file; In this tutorial, you will learn how to download files from server in node js + express+ rest API.

How to Download File From Rest API in Node js Express

Let’s follow the following steps to download files from rest api in node js express app:

  • 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

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.

Recommended Node JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

2 replies to Node js Download File From Rest API

  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *