A Basic Information Site Server built Using Node.Js

Roland Sankara
11 min readApr 27, 2020

--

If you feel totally green about Node.js and what it really is, then I guess you have landed onto the right article that will help walk you through what Node is, where it is used, when to use it, and the Node Architecture.

As I strive to bring you up to speed with node.js we shall go through the creation of a simple node.js information site that will hopefully paint a clear picture of the capabilities of node.js as we get along with this project. By the end of this blog, I hope you will be confident enough to start leveraging node.js in your projects especially if you looking into back-end development.

🔖Table of Contents.

1. What is Node.js?
2. How Node.js works
3. Build a basic information site server with Node.js
4. Github repository for this project 🚀

🤔 1. What is Node.js?

Node.js an open-source and cross-platform runtime environment for executing JavaScript code outside of a web browser.

So, at its most basic level, Node simply allows you to run JavaScript code locally( on your computer) or a server without using a web-browser.

This allows developers to use JavaScript to accomplish pretty much anything that other popular server-side languages such as Ruby, PHP, C#, and Python can do.

Node is often used to build back-end services which are well known as APIs (Application Programming Interfaces) which in simple terms refer to the services that power client applications such as web and mobile applications.

Node is also ideal for building highly scalable, data-intensive, and real-time apps.

Node’s Architecture.

You might be wondering why node.js is referred to as a runtime environment.

Well before node.js was created, JavaScript could only be executed in browsers. Browsers have a JavaScript Engine that converts JavaScript code into machine code for computers to understand.

For example, Chrome uses a JavaScript Engine called V8 while Firefox uses spidermonkey.

And it’s because of this variety of JavaScript engines that sometimes makes JavaScript code behave differently from one browser to another. So a browser provides a runtime environment for JavaScript code to be executed.

In 2009 Rayan Dahl the creator of Node came up with a brilliant idea, he thought it would be great to execute JavaScript outside of a browser so he took Chrome’s V8 engine which happens to be the fastest JavaScript engine and then embedded it into a C++ program and called that program Node.

So similar to a browser, node.js is a runtime environment for executing JavaScript code and it also contains certain objects that provide an environment for JavaScript though these objects are different from the environment objects in browsers.

For example, the document object or the window object in browsers don’t exist in node.js. Modules in node.js give us more interesting capabilities such as being able to work with the File System, the ability to listen of requests on a given port and so on which can’t be done in the browser.

🔎 2. How Node Works?

The reason why Node is highly scalable is because of its non-blocking or Asynchronous event-driven nature. Asynchronous in this context means that when you write your code you do not try to predict the exact sequence in which every line will run. Instead, you write your code as a collection of smaller functions that get called in response to specific events such as a network request (event-driven).

In node.js, a single thread handles all requests. When a request arrives, that single thread is used to handle that request. If the request needs a database to be queried, the thread doesn’t have to wait for the database to return the data. While the database is still executing our query, the thread will be used to handle another request and then when the database gets the data to the query, it places it into an Event Queue.

Node continuously monitors that Queue in the background and when it finds an event in that queue it will take it out and process it. Therefore this kind of Architecture makes node.js very ideal for a building I/O intensive applications or real-time applications.

So hope you now have some understanding of Node.js.

🌱 3. Basic Information site server with Node.js

To help you get up to speed with the basics of node I will be taking you through the creation of a basic information site server.

Before we can go any further, let’s first go through the prerequisites.👍

Prerequisites.💡

  • Install Node.
    To install Node, visit https://nodejs.org and then download the recommended version of Node. Go through the step-by-step installation process until you finish.
  • Your need a Code editor.
    You should have a code editor which in my case will be Visual Studio Code. Visit https://code.visualstudio.com to download Visual Studio code and then go through the step-by-step installation process.

Project Description and Instructions.

We shall create a very basic information site that contains 4 pages:
index, about, contact-me, and 404.

  • Create your node.js server file index.js and add the code needed to serve the right page according to the URL.
  • localhost:8080 should take users to index.html
  • localhost:8080/about should take users to about.html
  • localhost:8080/contact-me should take users to contact-me.html
  • 404.html should display any time the user tries to go to a page not listed above.

So let’s start on with our project.

We have to first ensure that we have installed Node on our machines. To do so, we have to open the command prompt in windows or the Terminal in Mac and Linux OS.

Run the following command: node --version;

If NodeJS is installed on your computer, the command entered will return the version of NodeJS that exists on your machine as shown below.

I have the node version 10.16.0 installed and chances are that your version could be different from mine but it’s okay.

So with Node installed, we can now create a directory for our project called Node-project and then open it in Visual studio code.

We use the following commands:

mkdir Node-project  // this creates a folder called Node-projectcd Node-project  // takes us to the folder you have createdcode .  // this command opens up the folder in VS code.

This is executed in the console of the command prompt as shown below.

A visual Studio code window will automatically pop up.
Create the following files in our directory;

  • index.js
  • index.html
  • about.html
  • contact-me.html
  • 404.html

Your VS code window should look like the example below.

Our main objective is to create a server that will render these pages based on a given URL provided by the user.

So you are at liberty to add content to your .html files that correspond to their names i.e. the about.html file is for the about page.

So let’s now open up the index.js file which will be our main module(file) for our node project.

In Node.js, each and every JavaScript file with the extension .js is considered a module. And as a matter of fact, Node comes with some inbuilt modules which offer a variety of functionalities.

In this project, we shall work with the HTTP module to create a simple Server, URL module to parse URL strings, and the File System module help us to work with the computer’s file system.

So let’s Create a Server using the HTTP module.

HTTP module:

This is one of Node’s inbuilt modules which allows Node.js to transfer data over the Hypertext Transfer Protocol (HTTP).

To include the HTTP module in our index.js file, use the require() method as shown below.

The HTTP module creates an HTTP server that listens for any requests made to it and gives a response back to the client.

Use the createServer() method to create an HTTP server like so:

The createServer() method takes in a request Listener function as a parameter. The request Listener function is the function that is executed each time the server gets a request.

The request listener function takes in two parameters i.e. request (req) and response (res). Each of these parameters represents an object i.e. the request parameter represents the incoming-message object while the response parameter represents the server-response object.

For example at lines 4 and 5 of the code shown above makes use of some of the methods in the server-response object i.e. res.write() and res.end().

server-response object methods explained👇 .

writeHead() method // Sends status and response headers to the clientwrite() method // Sends text, or a text stream, to the clientend() method // Signals that the server should consider that the response is complete

The .listen() method at the bottom takes in a port value in our case 8080, which the Server object will listen on so as to execute the requester Function.

Therefore, in order to run a Node application, you type the following command in either the inbuilt terminal in VS code or in your Command Prompt window.

Type: node index.js

And press Enter like so:

So at this point open up your browser and type localhost:8080 in the address bar and this should pop up;

Viola…… you have successfully created a node.js server. 🎉

This is evidenced by the Hello World string displayed on the page when you make a request to localhost:8080 through your browser.

Now we let’s look at manipulating the file System inbuilt module in Node so as to have access to the files in our Node project folder.

File System Module:

This module allows you to work with the file system on your computer. To include the File System module in our index.js file, we use the require() method:

const fs = require(‘fs’);

The File System has methods that help you to Read, Create, Update, delete, and rename files.

The fs.readFile() method is used to read a file’s contents, now let’s try to put it into use.

As we can observe, the fs.readFile() method takes in two parameters that is the URL/file path and a callback function which takes up two parameters that is the Error and the data objects.

So our implementation shows a file path “./index.html” and therefore when a request is made with the given file path. Node will, therefore, be able to access the file and then the data object which contains the contents of the file will be sent to the client by the help of the res.write(data) method.

Please note res.writeHead(200, {‘Content-Type’:’text/html’}) 

Sends status of 200 (OK) and response headers to the client i.e. {‘Content-Type’:’text/html’} which specifies to the browser that the data is an html page.

Alright, we can try to run our program in the terminal to see our results. As below remember to enter the “localhost:8080” in the address bar of the browser.

Wow isn’t that cool……😂 I hope you already feel amazed by Node.js … anyway let’s continue.

We are going to make use of the URL module which will help us parse the URL that we place in the address bar. We shall then use the pathname from the URL and then pass it into the fs.readFile() method to then enable a page to be rendered.

URL module:

The URL module splits up a web address into readable parts.

To include the URL module in our index.js file, we use the require() method.

const url = require(‘url’);

Parse an address with the url.parse() method, and it will return a URL object with each part of the address as it’s properties i.e. the host, pathname, query, and search properties.

So in our case, we are interested in the pathname property that will help us link to a file in the file system.

We shall store the URL object in a variable called path:

const path = url.parse(req.url, true) // req.url refers to the web URL placed in the browser address bar.

So then to obtain the pathname of the URL, we use the pathname method of the URL object. i.e

const filename = path.pathname // so we have to add the “.” prefix and the “.html” suffix to the URL pathname so that we are able to access the file via the file system.

🎉 Hack to completion

So I'll let you hack the rest of the code to completion especially the concept of handling the errors. But otherwise when here is my complete solution to our project. This is the index.js implementation.

Notice that errors are handled by sending a 404.html file to the browser when a user enters a URL pathname that does not exist.

So to be able to run this Node application, just open up your inbuilt terminal in VS code then type:

node index.js // to start our application 

Then open up your browser and then try to enter something like

localhost:8080 // then suffix this with something like /about,/contact-me to see the result.

Okay, that is all with our Basic information site built on top of Node. I hope this resource has indeed helped to bring you up to speed with Node.js.

I would like to however demystify the notion held by many that think Node.js is a framework or a programming language. Please understand that Node.js is just a runtime environment to run JavaScript on locally.

Thanks for following through this blog up until this point and before I sign out, here are some resources on NodeJS since this blog has covered just the tip of the Node iceberg.

References:

Adios✌ From me  /*** Hit Applause👏 if you found this article  Insightful***/

--

--

Roland Sankara

Fullstack Web Developer | Technical Writer | Passionate about tech mentorship