Open In App

Deploying Node.js Applications

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

To show how to deploy a nodejs app, we are first going to create a sample application for a better understanding of the process. 
I have created a directory/folder “example” for my sample project.
Before procceding, make sure you have installed nodejs and git on your system
Now, open the command line and cd inside the example(or whatever is the name of your project folder) directory
Follow the following steps to create the sample application for this tutorial
STEP 1: Create a “package.json” file using the following command
 

npm init

 

npm init

STEP 2: Create a file called “app.js” inside your project folder
STEP 3: Create a html file “head.html”
Fill the file with the following content 
This will be the homepage of our app which is connected to another page via hyperlink.
 

html




<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
  
    <h1>This is the Homepage</h1>
      
<p><a href="/tailPage">Go to Next Page</a></p>
  
  
</body>


STEP 4: Create another html file “tail.html” 
Content of tail.html is 
 

html




<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
  
    <h1>WORKING</h1>
  
</body>


STEP 5: Open “app.js” file created in step 2 and copy paste the following code in it 
 

javascript




var http = require('http');
var fs = require('fs'); // to get data from html file
  
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
  
    // req.url stores the path in the url
    var url = req.url;
    if (url === "/") {
// fs.readFile looks for the HTML file
// the first parameter is the path to the HTML page
// the second is the call back function
// if no file is found the function gives an error
// if the file is successfully found, the content of the file are contained in pgres
        fs.readFile("head.html", function (err, pgres) {
            if (err)
                res.write("HEAD.HTML NOT FOUND");
            else {
                // The following 3 lines
                // are responsible for sending the html file
                // and ends the response process
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
    else if (url === "/tailPage") {
        fs.readFile("tail.html", function (err, pgres) {
            if (err)
                res.write("TAIL.HTML NOT FOUND");
            else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
     
}).listen(3000, function () {
    console.log("SERVER STARTED PORT: 3000");
});


javascript




var http = require('http');
var fs = require('fs'); // to get data from html file
  
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
  
    // req.url stores the path in the url
    var url = req.url;
    if (url === "/") {
// fs.readFile looks for the HTML file
// the first parameter is the path to the HTML page
// the second is the call back function
// if no file is found the function gives an error
// if the file is successfully found, the content of the file are contained in pgres
        fs.readFile("head.html", function (err, pgres) {
            if (err)
                res.write("HEAD.HTML NOT FOUND");
            else {
                // The following 3 lines
                // are responsible for sending the html file
                // and ends the response process
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
    else if (url === "/tailPage") {
        fs.readFile("tail.html", function (err, pgres) {
            if (err)
                res.write("TAIL.HTML NOT FOUND");
            else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
     
}).listen(3000, function () {
    console.log("SERVER STARTED PORT: 3000");
});


Now, the above code displays the “head.html” file as the homepage which is connected to “tail.html”
STEP 6: Open the terminal again and write the following command to run the server 
 

node app.js

 

To see your application running, type “localhost:3000” in your browser as URL.
We have successfully created the sample application, we are now going to deploy it on the web.
There’s are many cloud platforms like AWS, Heroku, Digital Ocean, etc.
 

Steps to Deploy Sample Application

For this example, we are going to use Heroku since it’s easy to use and you can use it to test your apps for free. The free versions have some limitations thus if you want to use the site for commercial business it is recommended to get a paid package. Since this is a tutorial we gonna use the free version.
NOTE: ALL THE COMMAND ARE PERFORMED INSIDE THE DIRECTORY/FOLDER WHICH CONTAINS YOUR PROJECT
STEP 1: Go to https://www.heroku.com/ and register.
STEP 2: After completing the registration process, login and go to https://dashboard.heroku.com/apps
Before Proceeding any further, make sure you have installed the latest version of Git on your PC.
STEP 3: Go to Getting Started on Heroku with Node.js and download the Heroku Cli for your system.
You can check if Heroku CLI is successfully installed or not by typing the command
 

heroku -v

it should look like this
 

STEP 4: Type 
 

heroku login

in the command line
 

Press any key to continue, it will open a new tab in your browser asking you to login in your Heroku account
 

Click on Log in Bottom
After you successfully log in, the command line will look like this
 

( Heroku might not connect to Git bash, so use Command Prompt or terminal if it’s taking very long to connect i.e. if you were using git bash)
STEP 5: Now, make sure we are using Git in the top level directory of our app. We can check if the directory have Git or not by the command 
 

git status

 

To make it a git directory, type the command 
 

git init

 

Now, type 
 

git add . 

in command line.
 

(Ignore the warning for now)
Now, we need to commit the files we have added to git. Type 
 

git commit -m "initial commit"

 

STEP 6: Create heruko app by command 
 

heroku create

 

This will create a git remote which is connected to our local git repository
STEP 7: Type 
 

git push heroku master

to deploy the app on heroku server
STEP 8: After deploying the app 
type 
 

heroku ps:scale web=1 

to make sure one instance of app is running
STEP 9: Type 
 

heroku open 

this will open a app in your browser.
Now, you might be getting a screen like this
 

Go to command line and type 
 

heroku logs 

to check for error. It helps to debug the application.
 

It says npm ERR! missing script: start
To fix this problem, we need to set up a start script, the start script tells the server to run “node app.js” after installing the packages.
STEP 10: To setup the start script, open package.json inside the example folder and type ‘ “start”: “node app.js” ‘ inside the “scripts” tag. 
See the image 
 

( DON’T FORGET THE COMMA ‘, ‘ )
STEP 11: Type the following command in command line 
We need to push the app to Heroku every time we make changes in it.
 

git add .
git commit -m "another commit"
git push heroku master
heroku open

STEP 12: There’s still a problem.The problem is still not fixed. We are using PORT: 3000 but Heroku doesn’t. Heroku uses a dynamic port, we cannot fix it to 3000. If we want our application to work on Heroku we need to add the following line in the app.js file
.listen(process.env.PORT || 3000, function(…));
app.js will now look like this
 

javascript




// Write Javascript code here
  
var http = require('http');
var fs = require('fs'); // to get data from html file
  
  
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
  
    // req.url stores the path in the url
    var url = req.url;
    if (url === "/") {
// fs.readFile looks for the html file
// the first parameter is the path to the html page
// the second is the call back function
// if no file is found the function gives an err
// if the file is successfully found, the content of the file are contained in pgres
        fs.readFile("head.html", function (err, pgres) {
            if (err)
                res.write("HEAD.HTML NOT FOUND");
            else {
                // The following 3 lines
                // are responsible for sending the html file
                // and ends the response process
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
    else if (url === "/tailPage") {
        fs.readFile("tail.html", function (err, pgres) {
            if (err)
                res.write("TAIL.HTML NOT FOUND");
            else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgres);
                res.end();
            }
        });
    }
  
}).listen(process.env.PORT || 3000, function () {
    console.log("SERVER STARTED PORT: 3000");
});


STEP 13: Again type
 

git add .
git commit -m "another commit"
git push heroku master
heroku open

 

 

Congratulations, you have successfully deployed your first web application.
NOTE: 
1. If your application uses MongoDB then you will have to deploy MongoDB server separately on some other cloud platform. 
2. I was having some problem connected git bash to Heroku that’s why I switched to CMD in between. So, I recommend not to use Git Bash.
 



Last Updated : 11 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads