Node.js as a HTTP Server - Building from scratch - Tutorial for Beginners
By: William Alexander in node.js Tutorials on 2018-08-04
This node.js tutorial is for a beginner to understand the basics of node.js from scratch. More specifically, this tutorial explores how node.js can be used as a HTTP server to handle HTTP requests and serve files. Since this assumes that you are just beginning to learn node.js, I will start from explaining what is node.js and how to install it and then continue with the step by step guide.
What is node.js?
First of all, it is good to know that node.js is free :). And it can be installed in almost all platforms including windows, linux, macos, unix etc. Although I am a linux fan (particularly ubuntu), in this tutorial we will use Windows as a development environment to learn. This is because, all of us use laptops or PCs to develop and it is always handy if everything required to code resides in our laptop for easy reference. However, the same can be achieved in an Ubuntu or mac system as well. Only the installation file will be different, the rest of the code will be same in all platforms.
Node.js is a server platform and it is open source. And the good news is that all node.js code is written in JavaScript :) isn't that great? You can use Node.js for any of your back-end applications. However, in this tutorial we will use Node.js as a HTTP Server. Node.js differs from other HTTP servers in a sense that it use asynchronous programming. To illustrate this, let us take an example of how a typical http server functions. When PHP, JSP or ASP handles a request, it runs the server code such as reading the file, executing it and then finally responding to the request with a response. This is done synchronously. But since they are multi-threaded they can handle multiple requests simultaneously. But in node.js it is single threaded but since it uses asynchronous programming, it accepts requests sends the task to the file system and returns back to handle next request. This greatly improves memory-handling and it is non-blocking. In this tutorial we will see how this is done.
How to install node.js?
Installing node.js is the simplest step in this tutorial. Just visit node.js download page and download the LTS version which is currently 8.11.x. Download the appropriate file. For windows you can download the .msi file for 64-bit and run the installation file. Once it is installed, you can just open a command prompt and type node -v and it should show the version 8.11.x. That's it, you are ready to run node.js applications.
The next thing you would need is a proper IDE to develop and write code. Although you can use any text editor such as notepad++, I personally recommend Atom. Just visit Atom Download Page and download and run the installer. Atom is a beautiful and elegant code editor that is free and open source. You can use it to organize projects and write beautifully formatted and color coded scripts that is pleasing to look at and easy to understand.
Now that you have installed the node.js server and the atom IDE, you are ready to start programming.
Node.js as a HTTP server
It is important to note that node.js can be used to develop any of your backend workflows and logic using JavaScript and it is not a HTTP Server. But the beauty of node.js depends on its available modules which are nothing but JavaScript Packages. One such module is the 'http' module. So if you want to use node.js as a HTTP server then you have to use this 'http' module. Use 'require' keyword to include or import modules in a node.js script. First open a command prompt and go to c:\Users\yourusername\ and create a new folder named 'nodejstutorial'. cd (change directory) to nodejstutorial so that all your program files will be created in this folder.
var http = require('http');
Now open Atom or any other IDE of your choice and create a new project. This will create a new project under the current directory. Create a new file and copy the following code in it.
var http = require("http"); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); res.end('This is my first node.js script'); }).listen(8080);
Save the file as 'first.js'. Congrats!!! You have created your first node.js script and it is going to be a HTTP server. To run this code, open a command prompt and change directory to c:\users\yourusername\nodejstutorial or the folder where you created this above script. Now just type 'node first.js'
c:\users\yourusername\nodejstutorial> node first.js
What you just did is to instruct node.js to execute the code from first.js. In first.js you created an instance of the http server to listen to port 8080. Therefore the node.js will continue to listen to port 8080 until you terminate by doing CTRL+C. To check your first script, open any browser and goto url http://localhost:8080/ and you should see the text 'This is my first node.js script' gets displayed in the browser.
Serving different content based on url
So far, you have made node.js to act as a HTTP server and serve a single page with some text. But of course, you would want node.js to do more and serve multiple pages instead of a single page. You can achieve this by using another module named 'url'. Let us create two files left.html and right.html with different text of course and let node.js serve these content depending on which url was requested by the user.
For this first create left.html in the same project (same folder)
<html> <head><title>This is left header</title></head> <body> <h1>This is left header</h1> <p>This is some left text</p> </body> </html>
Now create the right.html in the same project (same folder)
<html> <head><title>This is right header</title></head> <body> <h1>This is right header</h1> <p>This is some right text</p> </body> </html>
Now edit the first.js script so that the request page can be extracted from the url and then serve the right page content. For this, in addition to 'url' module we have to use the 'fs' module which is the file system module that handles file handling such as reading, writing, appending, deleting files. In this case, we just want to read the files left.html and right.html and get its content.
Open first.js and edit the script as below:
var http = require("http"); var url = require('url'); var fs = require('fs'); http.createServer(function(req,res){ var q = url.parse(req.url,true); var filename = "." + q.pathname; fs.readFile(filename, function(err,data){ if(err){ res.writeHead(404,{'Content-Type':'text/html'}); return res.end('404 File not found'); } res.writeHead(200,{'Content-Type':'text/html'}); res.end(data); }); }).listen(8080);
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
Most Viewed Articles (in node.js ) |
Latest Articles (in node.js) |
Comments