In This web development tutorial you are going to create your very first server using node.js with witch you can then serve you own website.

Donation!

Buy me a Pizza
Hi, if you like my content and you wish to give back you can buy me a Pizza!
$7.00

Buy me a Pizza
Hi, if you like my content and you wish to give back you can buy me a Pizza!
$7.00
Project overview:
- Project requirements
- Require the HTTP library
- Creating the Hostname and the Port
- Crate a server function
- Listen with your server
- Test the server
- Rendering HTML files
- The file system
- Refactoring the code
Project prerequierments
In order to follow along with this project you first need to have node.js installed. If you do not have node.js and npm orlady on you machine, thn I would sougest checking out my previous tutorial on How to install NodeJS with NPM on Windows and Mac and then come back to this on. But if you already have node.js installed then you can skip this step and we can move on.
Require the HTTP library
HTTP stand short for hyper text transfer protocol, witch is used for fetching resources such as HTML documents, then you are going to assign it to a variable.
const http = require("http");
Creating the Hostname and the Port
Next you need to create a Hostname and a port on witch your server can listen to. This is easily done by giving a IP address to the hostname and a 4 digit number to the port.
Hostname:
const hostname = "127.0.0.1";
Port:
const PORT = 2080;
Crate a server function
Now we can actually create the server by assigning to the http the create server function witch is going to take a callback function with two parameters,these are the request req and the response res parameters.
const server = http.createServer((req, res) => { }
Listen with your server
Now that you have your server function, the next step will be to assign it to a PORT to listen to, in witch case you can use the PORT that you created.
server.listen(PORT, (error) => { if (error) { console.log(
You have an error,ParseError: KaTeX parse error: Expected ‘EOF’, got ‘}’ at position 14: {error}`); }̲ else { con…{hostname}:${PORT}/); } });
Test the server
It is time to test run the server a see if it works, and for this you just need to type in to the console node (the name of the file) server.js
. If the server is up and running you can also stop the server by tapping ctrl + c bought on mac and windows.
Test response
Next lets use our server function in order to return some kind of response to the user. For this we can use response with()
its write method, to write anything that we wont as a response to our user.
Then in order to end our response you can use the end()
method on the response. now we can call upon our server again with node server.js and after that open up a browser and go to localhost:2080 or you can just click on http address in the console holding down cmd on the mac and ctrl on the PC an clicking on the link.
const server = http.createServer((req, res) => {
res.write("Hello! from the node server.");
res.end();}
Rendering HTML files
Now lets render a html file in the browser throughout our server. For this you need to create a generic index.html
file.
In order to render a HTML file we first need to call the writeHead method witch send a response header to the request.The status code is a 3-digit HTTP status code, like 404. But 404 is a bad response witch means that something went wrong and we don’t want that so instead we are going to use a status of 200 with means that everything is ok. After that you need to set the content type witch is a key-value pair { "Content-Type": "text/html" }
.
res.writeHead(200, { "Content-Type": "text/html" });
The file system
The next step will be to import another library from node witch is the fs (file system) method, this is used to read files on your computer.
const fs = require("fs");
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404);
res.write("Error : File not found");
} else {
res.write(data);
}
res.end();
});
Final code
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404);
res.write("Error : File not found");
} else {
res.write(data);
}
res.end();
});
});
Refactor the code
http .createServer(function (req, res) { fs.readFile("index.html", function (err, data) { res.writeHead(200, { "Content-Type": "text/html" }); res.write(data); return res.end(); }); }) .listen(PORT);
What the video version on YouTube
Become a web developer!
Learn HTML CSS & Sass JavaScript Bootstrap and more...

1 thought on “Hot to create a server using Node.js”