• Node.js Video Tutorials

Node.js - Web Module



What is a Web Server?

The http module in Node.js enables data transfer between the server and client over the Hyper Text Transfer Protocol (HTTP). The createServer() function in http module creates an instance of Node.js http server. It listens to the incoming requests from other http clients over the designated host and port.

The Node.js server is a software application which handles HTTP requests sent by the HTTP client, like web browsers, and returns web pages in response to the clients. Web servers usually deliver html documents along with images, style sheets, and scripts.

Most of the web servers support server-side scripts, using scripting languages or redirecting the task to an application server which retrieves data from a database and performs complex logic and then sends a result to the HTTP client through the Web server.

Web Application Architecture

A Web application is usually divided into four layers −

Web Architecture
  • Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server.

  • Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response.

  • Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs.

  • Data − This layer contains the databases or any other source of data.

Creating a Web Server using Node

Node.js provides an http module which can be used to create an HTTP client of a server. Following is the bare minimum structure of the HTTP server which listens at 5000 port.

Create a js file named server.js −

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

// Create a server
http.createServer( function (request, response) {  
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
   
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
   
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
      } else {
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         // Write the content of the file to response body
         console.log(data.toString());
         response.write(data.toString());		
      }
      
      // Send the response body 
      response.end();
   });   
}).listen(5000);

// Console will print the message
console.log('Server running at http://127.0.0.1:5000/');

The createServer() function starts listening for client requests at the 5000 port of localhost. The Http Request and Server Response objects are provided internally by the Nde.js server. It fetches the URL of HTML file requested by the HTTP client. The callback function to the createServer() function reads the requested file, and writes its contents as the server’s response.

You can send a HTTP request from a browser on the server machine itself. Run the aboce server.js file, and enter http://localhost:5000/index.html as the URL in a browser window. The contents of index.html page will be rendered.

Send a request for any other existing web page, such as http://localhost:5000/hello.html, and the requested page will be rendered.

Creating Web client using Node

A web client can be created using http module. Let's check the following example.

Create a js file named client.js (Save this file in another folder, not in the folder containing server.js script) −

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

// Options to be used by request 
var options = {
   host: 'localhost',
   port: '5000',
   path: path.join('/',process.argv[2]) 
};
var body = '';
// Callback function is used to deal with response
var callback = function(response) {
   // Continuously update stream with data
   
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // Data received completely.
      console.log(body);
      fs.writeFile(options.path.substr(1), body, function (err) { 
        if (err)
            console.log(err);
        else
            console.log('Write operation complete.');
      });
      
   });
}
// Make a request to the server
var req = http.request(options, callback);
req.end();

This client script sends a HTTP request for a webpage given as a command-line argument. For example −

node main.js index.html

The name of the file is the argv[2] in the argument list. It is used as the path parameter in the options parameter to be passed to the http.request() method. Once the server accepts this request, its contents are written in the response stream. The client.js receives this response and writes the data received as a new file in the client's folder.

Run the server code first. From another terminal, run the client code. You will see the requested HTML file created in the client folder.

Advertisements