Table of contents
1.
Introduction
2.
Steps to Deploy NodeJs Application
3.
Frequently Asked Questions
3.1.
What is NodeJs?
3.2.
What are the applications of NodeJs?
3.3.
How do I start with Node.js after I installed it?
4.
Conclusion
Last Updated: Mar 27, 2024

How to Deploy NodeJs Application

Author Ankit kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

NodeJs is a cross-platform runtime environment that allows developers to execute application code on a private server instead of a web browser. It is built for writing server-side applications with javascript. It is a technology of choice for a large number of developers. It's used in production by many companies like Netflix, uber, etc.

In order to show how to deploy NodeJs applications, we’re gonna make a sample application named ‘sample1’.Now,the next step is to download and install nodeJs. After that, follow the steps below:

Steps to Deploy NodeJs Application

STEP 1: Create a “package.json” file using the following command

npm init

 

STEP 2: Open your project folder and create a js file and name it “app.js”.

STEP 3: Inside your project folder, create a html file and name it “head.html”.

Inside the html file, fill the following code

<!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 under same folder and name it “tail.html”.

Fill in the following code inside your file

<!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 5: Open “app.js” file and fill the following code nodejs application.

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("head.html", function (err, pgres) {
            if (err)
                res.write("HEAD.HTML NOT FOUND");
            else {
                
                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");
});

 

STEP 6: Open the terminal again and write the following command to run the server 

node app.js

 

Now, if you type “localhost:3000” in your browser, you will see your application running.

We have completed our basic part, now its time to deploy it into the web. There are many cloud platforms like digital ocean, heroku etc. For our example, we'll be using heroku as it is easy to use and free for learners node js application.

Before moving further, it's recommended to install git on your system.

STEP 1: Go to heroku site and get registered.

STEP 2: After completing the registration, go to https://dashboard.heroku.com/apps 

STEP 3: Download heroku CLI for your system.

STEP 4: In the command line, type

heroku login

 

After successful login, following will be shown

STEP 5 : Type

git init

 

Now type

git add .

 

Now, we need to commit the files we have added to git. Type

git commit -m "initial commit"

 

STEP 6 : Now, create the heroku app by command

heroku create

 

This will create a git remote which is connected to our local git repository in nodejs application

STEP 7 : Type the following to deploy the app on heroku server

git push heroku master

 

STEP 8 : In order to make sure one instance of the app is running, type

heroku ps:scale web=1

 

STEP 9: To open the app in the browser, type

heroku open

 

This will open as:

Go to command line and open logs to check for errors i.

It's saying “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 : Open “package.json” and type “start”: “node app.js” inside the scripts tag.

There is one more problem right now.We are using PORT: 3000 but Heroku doesn’t. Heroku is using dynamic port. Therefore, we need to change the code as follows in app.js file in nodejs application.

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("head.html", function (err, pgres) {
            if (err)
                res.write("HEAD.HTML NOT FOUND");
            else {
                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 11 : Again type in nodejs application

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

 

Hurray! Your first web application deployed.

Check out most important Git Interview Questions here.

Frequently Asked Questions

What is NodeJs?

NodeJs is a cross-platform runtime environment that allows developers to execute application code on a private server instead of a web browser.

What are the applications of NodeJs?

With NodeJs, one can build single page applications, real time chat apps, IoT etc.

How do I start with Node.js after I installed it?

Once we have installed Node.js, let's build our first web server in nodejs application. Create a file named app.js containing the following contents:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Now, run your web server using node app.js. Visit http://localhost:3000 and you will see a message saying "Hello World".

Conclusion

In this article, we have discussed how to deploy a NodeJs application on a web server.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, interview puzzles, take a look at the interview experiences, and interview bundle for placement preparations.

We hope that this blog has helped you enhance your knowledge regarding puzzles, and if you liked this blog, check other links.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass