13-Dec-2022
.
Admin
Hello Friends,
This tutorial will provide an example of how to download files from rest API in node js. We will help you to give an example of a node.js download file to client example with rest API. You can see download a file from the nodejs server using node js. Let's get started with how to download files from the node.js server.
Node js + express rest API download file; In this tutorial, you will learn how to download files from the server in node js + express+ rest API.
Step 1: Create Node Express js App
Execute the following command on the terminal to create the node js app:
mkdir my-app
cd my-app
npm init
Step 2: Install Node Modules
Execute the following command on the 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 the server.js file and import the 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 the terminal to start the node express js server:
//run the below command
npm start
I hope it can help you...
#Node JS