Creating a simple web server with Node.js

Node.js is a free and open-source software that enables developers to build server-side and networking applications using JavaScript as the programming language. It is quick and effective thanks to its non-blocking event-driven I/O mechanismA method of processing input and output operations that does not stop other code from running. It allows Node.js to do several tasks at the same time without having to wait for each task to finish., making it perfect for real-time applications with plenty of data. It is easy to use and can be quickly deployed for building modern applications with great scalability and performance.

In this Answer, we'll build a web server with Node.js’s HTTPHyper Text Transfer Protocol (HTTP) is used to create a connection with the server and send responses to the browser or the application making the request. We request data from a web server, and the server returns HTML content as a response while loading a webpage. module, which will allow us to make requests and send back responses.

Setting up the project

To set up the project, open the terminal and create a folder with the mkdir <folder-name> command. Then, navigate to this folder using cd <folder-name> and configure the environment by initializing a new Node.js project with the yarn init-y command in this folder.

mkdir node-webserver
cd node-webserver
yarn init -y
Initializing the project

Building the web server

Now, open the folder in the editor of your choice and create a new file index.js and import the HTTP module from the node as shown below:

const http = require("http");
Import the http module

There is no need to install anything to use the HTTP module, because it is included in the node installation. Next, we create an HTTP Server object, which returns a new instance of the HttpServer class using the code below:

const server = http.createServer();
Initialize the server

Before listening for any event, create two constants, PORT and HOST:

const PORT = 3000;
const HOST = "localhost"; // or 127.0.0.1
Declare the PORT and HOST constants

These variables will be used when we start listening to the server. We need to create a requestListener function to start listening for the request event, as shown below:

const requestListener = (request, response) => {
response.writeHead(200);
response.end("Hello, World!");
};
The requestListener function

The requestListener function handles requests coming into the server and sends back the server's response. It has two parameters: request and response. The request parameter represents the request that was made to the server, and the response parameter represents the response that the server will send to the client.

The response.writeHead method writes the response header to the request. The 200 is the HTTP status code, which means the request is successful.

The response.end method ends the response and sends it back to the client. The "Hello, World!" is the response body. The HTTP protocol requires a response body, even if it is empty.

Next, we'll listen for the request event:

server.on("request", requestListener);
Listen for the request event

In the code above, requestListener will be called every time a request is made to the server.

We can now start the server to listen for connections.

server.listen(PORT, HOST, () => {
console.log(`Server running at http://${HOST}:${PORT}/`);
});
Listen for connections on the server

The server is bound to both the PORT and HOST using the listen method. The listen method takes three arguments: a callback that gets called when the server starts listening, the PORT, and the HOST. The callback logs a message to the console to show that the server is open for connections.

The final index.js file looks like this:

const http = require("http");
const server = http.createServer();
const PORT = 3000;
const HOST = "localhost";
const requestListener = (request, response) => {
response.writeHead(200);
response.end("Hello, World!");
};
server.on("request", requestListener);
server.listen(PORT, HOST, () => {
console.log(`Server running at http://${HOST}:${PORT}/`);
});
The index.js file

Testing the web server

We need to run the index.js file to see our code in action. For this purpose, we open the terminal and run the following code to start the server:

node index.js
Start the web server

Let’s test the webserver on our platform by running the following widget:

const http = require("http");

const server = http.createServer();

const PORT = 3000;
const HOST = "0.0.0.0";

const requestListener = (request, response) => {
  response.writeHead(200);
  response.end("Hello, World!");
};

server.on("request", requestListener);

server.listen(PORT, HOST, () => {
  console.log(`Server running at http://${HOST}:${PORT}/`);
});
A simple web server with Node.js

Free Resources