Let's create a Web Server in JavaScript using:
Node.js
All the code is available in the GitHub repository
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
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
mkdir my-web-server
Step into it
cd my-web-server
Create an empty file
touch app.js
Open the folder with your favorite IDE. If you have Visual Studio Code, you can type this from the terminal
code .
You should now have a folder similar to this one
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.
const http = require('http');
Next, we will create a variable that tells the web server what port it should listen to.
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.
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.
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
node app.js
You should get an output of something like this.
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.
const server = http.createServer((req, res) => {
res.write("Hello World!");
res.end();
});
Now when you run the command
node app.js
you should see Hello World written in localhost:3000
Instead of just displaying the plain text in the browser, we need HTML to render in the web server.
Create a new HTML file
touch index.html
Type the following code
<!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.
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
// inside app.js
const fs = require('fs');
Let's make some changes in createServer function.
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.
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);
}
});
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
Do not forget to follow me on Twitter, GitHub, Linkedin for more such awesome content.
That's all.
If you have any questions, drop a comment below.
Top comments (0)