×

Search anything:

Downloading server files in Node.JS application

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

Reading time: 30 minutes | Coding time: 15 minutes

In this article, you will learn how to download server files in Node.js application. Now, to do that I will be using Express framework. I am using express framework here since its one of the most popular nodejs framework. And with express its very easy to download file from Node.js server, Since express framework provides helper function.

res.download(path [, filename] [, options] [, fn])

So let's get started assuming that you have already installed nodejs in your pc.

1. Get started

Now type the following commands in your terminal or cmd

mkdir nodejs-app

This will create a folder in which your nodejs application will reside.

cd nodejs-app

Change the directory

npm init

This will create your npm package that will contain information about your nodejs application,just keep everything to default.

npm install express --save

Now install express module in your nodejs application.

code .

Now open your text editor,in my case i will be using visual studio code.This is the shortcut key to open visual studio code.

2.Let's code

Now in your text editor you will see a file with a name - package.json
open that file it will look something like this:-

{
  "name": "download_server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Now create a javascript file with the same name as main that is index.js.

Inside that file write the following code.

var app = require('express')();
var http = require('http').Server(app);
//Using direct file URL
app.get('/',function(req,res){
    res.download(__dirname +'/upload_folder/ichigo.jpeg','ichigo.jpeg');
})
http.listen(3000,function(){
    console.log('Server is live on server ' + 3000);
})

Now go to terminal and type the following command

node index.js

And your application will be running in the localhost:3000
Now let's review the above code line by line.

var app = require('express')();

Or you can write it like

var express = require('express');
var app = express();

Both of these are same.
Now what is happening here is that we importing express module in our file to use it's functions and components.

var http = require('http').Server(app);

Now like express module we are importing http module to use it's functions to create a server which we can use.

app.get('/',function(req,res){
    res.download(__dirname +'/upload_folder/ichigo.jpeg','ichigo.jpeg');
})

The first function is get function Syntax: app.get(path, callback [, callback ...]) it routes HTTP GET requests to the specified path with the specified callback functions. You can further read about GET function here

Next function is the download function which is responsible for downloading server file. In the function filepath is '/upload_folder/ichigo.jpeg'
and filename is 'ichigo.jpeg' it's an jpeg image you can choose any thing you like and one more thing the upload_folder should be in your nodejs-app folder.

http.listen(3000,function(){
    console.log('Server is live on server ' + 3000);
})

With this your server will be up and running on localhost:3000.

But without any user interface this program is dull and boring now to add some UI first create a html file in your project folder you can name it yourself.After that write below code in it.

<html>
    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src = "https://socket.io/socket.io.js"></script>
    </head>
    <body>
        <button id = "btn_download">Download</button>
        <script type="text/javascript">
        $("#btn_download").click(function(){
            window.open('/download');
        })
        </script>
    </body>
</html>

What this will do is add a download button on your server to download server file but first we have to access this file in order to make it possible.
So, add changes to your index.js file.

var express = require('express');
var app = express();
var http = require('http').Server(app);

//This will add button to link to your download page
//res.sendfile(link of html file in your pc)

app.get('/',function(req,res){ 
  res.sendFile('/home/prateek/Documents/nodejs/open_genus/download_server/html_file.html');
})
app.get('/download',function(req,res){
    res.download(__dirname +'/upload_folder/ichigo.jpeg','ichigo.jpeg');
})
http.listen(3000,function(){
    console.log('Server is live on server ' + 3000);
})

Again run your application and it will look something like this:

Screenshot-from-2020-02-21-23-28-37-1

4. Conclusion

In this article we learned how to download the files in node.js.Download file from Node.js server is easy, We don't need to do much stuff here.That’s all for now. Thank you for reading and I hope this article will be very helpful to understand file download from Node.js server.

5. Extra features

After downloading a file, if you want your application to present a different page like a “thank you” page. Follow the below steps:

  1. Create a new html file and name it thankyou.html
  2. Add following code
<html>
    <body>
       <h1>Thank You for the download</h1>  
    </body>
</html>

I made it simple if you want you add more feature like background color or different fonts.

  1. Add following code in your index.js file
app.get('/Thanks',function(req,res){
res.sendFile('/home/prateek/Documents/nodejs/open_genus/Download_server/thankyou.html')//Full path of thankyou.html file
})
  1. Now add changes to your html_file.html
window.open('/Thanks');
//Add this command just after
//window.open('/download');

Above changes with redirect you to a page which will look like:

Screenshot-from-2020-02-23-16-39-37

Question

How can plain HTML be rendered in express JS?

res.sendfile()
res.render()
app.get()
All of the above
There’s no need to render HTML with the res.render () function. If there’s a specific file, then you should use the res.sendFile () function. If any assets are being served from a dictionary, then express.static () middleware function needs to be used.

You can further read about the download function in official documentation link which is the central utility in this feature.

With this article at OpenGenus, you have the complete idea of downloading server files in Node.JS application. Enjoy.

Downloading server files in Node.JS application
Share this