JavaScript Web Server using Nodejs
Tags: beginners, webdev, node, tutorial
Published: 2023-04-20 01:33:24

Let's create a Web Server in JavaScript using:

Node.js

All the code is available in the [GitHub repository](https://github.com/edsondsouza/web-server)

## Introduction

Hai, my name is Edson Sooraj Dsouza. I am currently on my journey to becoming a full-stack web3 developer. Recently I built a web server in JavaScript using Nodejs.

In this blog, I will share with you a step-by-step guide in building your first web server using Nodejs.

I am super excited. Let's get started!

## Prerequisites

_None_. **But it is better if you have a basic understanding of how backend of the web server work.**

I will share the [link here](https://youtu.be/4r6WdaY3SOA)

> Make sure Git Bash and Nodejs are installed in your system.

## Step-by-step guide

Here is a step-by-step guide.

Open the Git Bash and pass the following commands

Create a new folder
```bash
mkdir my-web-server
```
Step into it
```bash
cd my-web-server
```
Create an empty file
```bash
touch app.js
```
Open the folder with your favorite IDE. If you have Visual Studio Code, you can type this from the terminal
```bash
code .
```
You should now have a folder similar to this one

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u67kwwylxgu8iu6tkorf.png)

Now let's start coding.

> Remember Nodejs is a JavaScript runtime that allows the JavaScript outside of the browser.

First, we need to get the _http module_ to start the server.
```javascript
const http = require('http');
```
Next, we will create a variable that tells the web server what port it should listen to.
```javascript
const port = 3000;
```
Now we will create a server using _http.createServer_ method. This method consists of a function that takes two parameters request and response.
```javascript
const server = http.createServer((req, res) => {
    
});
```
For now, keep this function empty.

The next thing we want to do is set up the server to listen to the port we want to.
```javascript
server.listen(port, (error) => {
  if (error) {
    console.log("Something went wrong", error);
  } else {
    console.log("Server is listening on port " + port);
  }
});
```
To check if our server is listening to the port, open up the terminal and pass the following command
```bash
node app.js
```
You should get an output of something like this.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u4wpz0bamised46ak96.png)

Now scroll up to the first function we created. Here we need to add the code that responds to the user every time the server runs.

We can do this by adding the following code.
```javascript
const server = http.createServer((req, res) => {
  res.write("Hello World!");
  res.end();
});
```
Now when you run the command
```bash
node app.js
```
you should see Hello World written in _localhost:3000_
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20xkteolqct15spaegdz.png)

Instead of just displaying the plain text in the browser, we need HTML to render in the web server.

Create a new HTML file
```bash
touch index.html
```
Type the following code
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My-Web-Server</title>
  </head>
  <body>
    <h1>This is HTML</h1>
  </body>
</html>
```
Now we need to tell the browser that we will be using HTML. We can do this by passing the following code to createServer function.
```javascript
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Hello World!");
  res.end();
});
```
Import a new module to read the contents of the HTML file
```javascript
// inside app.js
const fs = require('fs');
```
Let's make some changes in createServer function.
```javascript
const server = http.createServer((req, res) => {
  // this function will be called every time a request is made to the server
  // we will add all the activities that we want to do when a request is made inside this function
  // we need to send the response to the client
  // we will tell the browser we are going to write html
  res.writeHead(200 /* status code */, {
    "Content-Type" /* This is one of the header */: "text/html",
  });
  fs.readFile("index.html", (error, data) => {
    if (error) {
      res.writeHead(404);
      res.write("Error: File Not Found");
    } else {
      res.write(data);
    }
    res.end();
  }); // this will read the file and return the data
});
```
Overall the code in _app.js_ should look like this.
```javascript
const http = require("http");
const fs = require("fs");

const port = 3000;

const server = http.createServer((req, res) => {
  res.writeHead(200, {"Content-Type": "text/html",
  });
  fs.readFile("index.html", (error, data) => {
    if (error) {
      res.writeHead(404);
      res.write("Error: File Not Found");
    } else {
      res.write(data);
    }
    res.end();
  });
});
server.listen(port, (error) => {
  if (error) {
    console.log("Something went wrong", error);
  } else {
    console.log("Server is listening on port " + port);
  }
});
```
Restart _localhost:3000_.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/drz0f25vs56defnco21m.png)

Congratulation 🎉 You just set up your first Web Server using Nodejs.

## Conclusion

This is a basic example of how you can build a Web Server using Node.js.

All the code is available in the [GitHub repository](https://github.com/edsondsouza/web-server)

Do not forget to follow me on [Twitter](https://twitter.com/edsondsouza), [GitHub](https://github.com/edsondsouza), [Linkedin](https://www.linkedin.com/in/edson-sooraj-dsouza-7b110a241/) for more such awesome content.

That's all. 
If you have any questions, drop a comment below.