Getting started with first Node JS Server with HTTP

Reading Time: 3 minutes

Introduction:

Node.js is a platform built on Chrome’s JavaScript Runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. If you wants to learn more about Node.js, you can refer here.

Before creating an actual “Hello, World!” application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important components −
  • Import required modules: We use the require directive to load Node.js modules
  • Create server − A server which will listen to client’s requests similar to Apache HTTP Server.
  • Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
Node.js = Runtime Environment + JavaScript Library

Prerequisites

This blog assumes that you are using Ubuntu 20.04. Before you begin, you should have a non-root user account with sudo privileges set up on your system. You can learn how to do this by following the Ubuntu 20.04 initial server setup tutorial.

To install Node.js:

To get this version, you can use the apt package manager. Refresh your local package index first by typing:

$ sudo apt update

Then install Node.js:

sudo apt install nodejs

Check that the install was successful by querying node for its version number:

$ node -v
Output

v10.19.0
Now let’s start to create Node.js Application:

Step 1 – Import Required Module

We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows −

var http = require("http");

Step 2 – Create Server

We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return “Hello World”.

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Listening to port 8081..');
The above code is enough to create an HTTP server which listens. Then waits for a request over 8081 port on the local machine.

Step 3 – Testing Request & Response

Let’s put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −

var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Listening to port 8081..');

Now execute the main.js to start the server as follows −

$ node main.js

Verify the Output. Server has started.

Listening to port 8081..

Make a Request to the Node.js Server

Open localhost:8081 in any browser and observe the following result.

Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081.

For live demo, you can refer here:

Conclusion:

In this blog, we’ve learn learnt the basic component which have been used in Node.js application and also how we can create our first node.js application and how we can test them too. Thus we can conclude that, it helps to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.

Hey there, I am glad you have reached the end of this post. If you liked this post or have some questions or want to discuss something let me know in the comment section. 

For more info you can check:

https://nodejs.org/en/docs/guides/getting-started-guide/

knoldus-advt-sticker

Written by 

Alka Vats is a Software Consultant at Knoldus. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

1 thought on “Getting started with first Node JS Server with HTTP4 min read

Comments are closed.