Node.JS Web Server

We have covered most of the basic node.js concepts. Now is the time to move towards more advanced node.js concepts. In this article we shall study what node.js web server is and how to create it via node.js. But first, lets see what a web server in general is.

A web server

When you type URL of some website in your browser and hit enter, you basically generate an HTTP request for a webpage located at a remote computer. That remote computer that serves your HTTP requests is basically a web server. So a web server can be defined as a computer that listens to HTTP requests from clients such as web browser, and sends backs HTTP response in the form an HTML page. However, if the request page contains some server side scripting e.g PHP or ASP.NET etc, the server forwards the page to Application server which processes the server side code, make database requests if any and sends back the corresponding HTML which is then sent to client by the web server.

Take a look at the following code. Here we create a simple node.js web server.

var http = require('http');
var fileSystem = require('fs');
var path = require('url');

http.createServer( function (request, response) {  
   var filepath = path.parse(request.url).pathname;
   console.log("Client request received for " + filepath);

   fileSystem.readFile(filepath.substr(1), function (err, page) {
      if (err) {

         response.writeHead(404, {'Content-Type': 'text/html'});
      }else {	

         response.writeHead(200, {'Content-Type': 'text/html'});	

console.log('Server listening for requests at');

Download the code Try the code

In the above example we use HTTP instance to create a web server by calling its “createServer” method. Create server is an asynchronous method which waits for the client requests for the execution of its callback function. As soon as client request is received, the contents of the requested file are read and sent to the client.

Sending Request to Web Server

To check if server is functioning correctly, create a file named “main.htm” and add the following code to it.

      <title>Welcome Page</title>
      <h1>Welcome to knowledge hills.</h1>

Download the code

Place the above file in the same directory where the code of your web server file is located.

Now type the following address in your browser, “”. This is basically a request the server we created, for the file “main.htm”. The server will send back the html contents of main.htm. In the browser you will see “Welcome to knowledge hills.” printed in h1 heading. This is basically how your browser read the contents of the html document i.e. “main.htm”

<<< Node.JS Global ObjectsNode.js HTTP Client >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .