Vishal

Posted on November 20th

How to create HTTP server with NodeJs - With or Without A Library

"In this tutorial we will know what is an HTTP server how can we create HTTP server with NodeJs"

How to create an HTTP server in NodeJs

We will see how to create a NodeJS HTTP server in this tutorial in two ways

  1. Using the HTTP library
  2. Using the net library i.e. Creating an HTTP server from scratch using TCP with NodeJS

What is an HTTP server?

An HTTP (Hyper Transfer Protocol) server serves you what you request like web pages and other content over the internet, it’s a program that runs on a server and responds on your request from a web server to a client, for example, when you enter any web address in your search engine and press enter your browser send a request to HTTP server and HTTP server return web page and other content as a response

An HTTP server works like a waiter and a restaurant, it’s like the waiter taking your order, going to the kitchen, taking food and bringing it back, and serve on your table here your order is your request and food is your response (e.g. web pages and other content).

HTTP servers work based on a client-server model. The client is a web browser, that sends requests to the server, and the server responds to the request by sending the requested information back to the client. the exchange of this all request and response handling by HTTP protocol, which defines how messages are arranged and transformed.

HTTP servers can handle lots of things, not web servers only can handle images, videos, files, and other types of content when you click on the link to watch images and videos and download files and videos your browser sends a request to the HTTP server hosting this content, and the server responds by sending the file and images back to the browser.

One of the best features of an HTTP server is, that it can host multiple websites on a single server Each website has its own domain name (like www.example.com) and the HTTP server uses a domain name to verify which website content to serve when it receives a request, its look like a restaurant with multiple menus, where which menu to give you depends on the table you are sitting.

HTTP servers also support lots of features to enhance security and performance. For example, they can encrypt data using HTTPS (HTTP Secure)to protect from eavesdropping and tampering. They can also cache frequency accessed to help speed up delivery and reduce server load.

In summary, an HTTP server is like a waiter for the Internet, serving clients web pages images, videos, and other content. It receives a request from the client and sends back the response using the HTTP protocol

How does the HTTP server work

When you search any URL from your browser to access any site, your browser sends a request to the HTTP server where that site is hosted then the server processes your request and sends back the requested data to the client

Features of HTTP server

There are lots of features that you can use in your daily life, even when you are browsing in a browser

  • HTTP servers can handle large data storage and can handle multiple websites on a single server
  • It allows to set up log files on the server to manage the error
  • it allows for the configuration of websites also
  • You can create FTP websites as webservers to move data from one site to another site easily
  • It helps to manage bandwidth that regulates the income traffic
  • it helps to create virtual directories

Advantages of HTTP server

Here is some list of HPPT server benefits

  • You can get important information to communicate with the hosting provide easily
  • it helps to manage the speed of downloading for any web-based application and improves performance very easily
  • It is manageable and flexible
  • you can customize it as you want
  • it helps to handle various application

Disadvantage of HTTP server

Sometimes you may see HTTP server is more expensive than an electronic web hosting practice

  • Sometimes you may see HTTP server is more expensive than an electronic web hosting practice
  • During high traffic, you may experience server crash
  • sometimes it's challenging to manage the hosting service on the HTTP server

What is NodeJs

Because we are creating an HTTP server with nodeJs then, we must have knowledge about nodeJs

NodeJs is one of the most powerful and open-source cross-platform javascript runtime environments, it’s a popular tool for almost all types of projects

it’s working on the v8 javascript engine, Node. js provides a runtime environment outside of the browser. we can make back-end applications using this same javascript programming language

NodeJS is used for building web applications for both client-side and server-side, it’s also used for creating APIs(Application Programming Interfaces) to serve data to the client applications, handle database operations, and perform other server-side tasks.

The best part of Node js is package managing, npm (node package manager), is the largest ecosystem in the world that allows developers to install, manage, and share reusable modules, making developers faster and more efficient.

One of the best parts of using NodeJs is its single programming language, javascript, which allows developers to use this both the client and server side we can also use it to manage databases, which means we can use it for back-end also.

The best part is, it can handle real-time applications, which is a good thing, which helps to communicate between client and server in real-time that helps developers to develop real-time communication applications, multiplayer games, and lots of things things

How to install NodeJs on Ubuntu

To install NodeJs on Ubuntu follow these steps

Step 1: Update the system

Open your terminal and run this command to check the package repository index is up-to-date

sudo apt update

Step 2: Download and Install NodeJs

You can install NodeJs using this command

sudo apt install nodejs

Step 3: Download and install NPM

npm is the package deal supervisor for Node.Js and is usually blanketed with the Node.Js setup. To install npm, you can run:

sudo apt install npm

Step 3: Check Node and NPM version

After set up, you can confirm if Node.Js and npm had been installed efficiently with the aid of checking their versions:

node -v
npm -v

Install Node.js using NodeSource Repository

You can install Node.js using the NodeSource repository, it provide more up-to-data version.

First, install the NodeSource and the curl utility

sudo apt install curl
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

Once NodeSource and curl installed then install the Node.js and npm

sudo apt install nodejs
sudo apt install npm

After installing check the version to verify

node -v
npm -v

Result

Node version:

v21.1.0

npm version:

10.2.0

If you want to download a specific version of NodeJs you need to download NVM and you can download NVM using curl

Download NVM

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

Check NVM Version

Verify the NVM version

nvm -v

If your NVM version is showing, it means you have successfully downloaded the NVM

Install a specific version of NodeJs

To download a specific version NodeJs run this command, in my case, I am downloading version 18

nvm install 18

Jump to another version

if you want to use another version of NodeJs make sure that version is already downloaded on your machine if it is already downloaded then run this command

nvm use 18

Set default Node version

Use a specific node version for the current terminal session

nvm alise default 18

Listing installed node version

If you want to check all installed node versions in your machine run this command

nvm ls

Uninstall a specific node version

If you want to uninstall any version of nodeJs then run this command in my case I am selecting 18

nvm uninstall 18

Let’s create a HTTP server

Very first we need to create a new file

touch server.js

In my case, I created this file named server.js

Very first we need to import http using require method

const http = require("http");

After importing the HTTP now let’s create a server using createServer() functionality

const server = http.createServer((req, res) => {
    res.end(("Hello from me"))
})

Here, when we create a server it sends a response and here we print a message “Hello from me” at the end of the response

After this all we need to listen this server on a unique port

server.listen(5000, "localhost", () => {
    console.log('server is running on port 5000');
})

In my case I'm using port 5000 you can change it as you want and I am printing a message also when our server starts

after this all we need to start our server, so let’s do it

node server.js

after running this command our server will be started

Here is the complete code

const http = require("http");

const server = http.createServer((req, res) => {
    res.end(("Hello from me"))
})

server.listen(5000, "localhost", () => {
    console.log('server is running on port 5000');
})

How to create HTTP server with NodeJs using net

First we will create a file named server.js

touch server.js

For creating HTTP server using net first we need to import net

const net = require('net');

After importing net, let’s create server

const server = net.createServer();

after creating server we need to write some code to create http server

server.on('connection', handleConnection);

function handleConnection(socket) {
  socket.on('data', (chunk) => {
    console.log('Received chunk:n', chunk.toString());
  });
  socket.write('HTTP/1.1 200 OKrnServer: my-web-serverrnContent-Length: 0rnrn');
}

Here we are calling a function handleConnection on new connections.

Not listen our server on unique port

server.listen(3000);

After writing this all code start our server with running this command

node server.js

Run this command to make a simple request using cURL

curl -v localhost:3000/some/url

After running this command you will see some output like this

Received chunk:
 GET /some/url HTTP/1.1
Host: localhost:3000
User-Agent: curl/8.2.1
Accept: */*

Now let send a post with some data

curl -v -XPOST -d'hello world' localhost:3000/some/url

Result

Received chunk:
 POST /some/url HTTP/1.1
Host: localhost:3000
User-Agent: curl/8.2.1
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded

hello world

If your result is looking like this it means everything is done

Here, is the full code

const net = require('net');
const server = net.createServer();
server.on('connection', handleConnection);
server.listen(3000);

function handleConnection(socket) {
  socket.on('data', (chunk) => {
    console.log('Received chunk:n', chunk.toString());
  });
  socket.write('HTTP/1.1 200 OKrnServer: my-web-serverrnContent-Length: 0rnrn');
}

Complete Code

The project is available on our GitHub : https://github.com/piehostHQ/node-http-server

Comments

Leave a comment.

Share your thoughts or ask a question to be added in the loop.