We now have a youtube channel. Subscribe!

Node.js | Web Module

Node.js Web Module


Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about Node.js Web Module.

What is a Web Server?

A web server is a software application and an underlying hardware that handles HTTP requests sent by the HTTP user agent, like web browsers, and then returns web pages in response to the user agent. Web servers usually delivers html documents along with images, style sheets, and scripts.

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

The Apache web server is one of the most commonly used web servers. It is an open source project.


Web Application Architecture

A web application is usually split into four layers -

Web Application Layers

  • Client - Has web browsers, mobile browsers, or the applications which can make HTTP requests to the web server.
  • Server - Has the web server which can intercept requests made by the clients and pass them the response.
  • Business - Has the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer using the database or some external programs.
  • Data - Has the database or any other source of data.

Creating a Web Server using Node

Node.js gives an http module which can be used to create an HTTP client of a server.

Example

Following is the bare minimum structure of the HTTP server which listens at 8081 port.

Let us create a js file, server.js making use of the following code -

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);
         
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      } else {	
         //Page found	  
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         // Write the content of the file to response body
         response.write(data.toString());		
      }
      
      // Send the response body 
      response.end();
   });   
}).listen(8081);

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

Next, let us create the following HTML file, index.html in the same directory where you created server.js -

<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!
   </body>
</html>

Now run the server.js to see the result -

$ node server.js

Output

Verify the output.

Server running at http://127.0.0.1:8081/

Make a request to Node.js Server

Open up http://127.0.0.1:8081/index.html in any web browser to see the following result -

nodejs_sample

Output

Verify the output at server end.

Server running at http://127.0.0.1:8081/
Request for /index.htm received.


Creating a Web client using Node

A web client can be created making use of http module. We are going to be looking at the following example below.

Example

Let us create a js file, client.js -

var http = require('http');

// Options to be used by request 
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// Callback function is used to deal with response
var callback = function(response) {
   // Continuously update stream with data
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // Data received completely.
      console.log(body);
   });
}
// Make a request to the server
var req = http.request(options, callback);
req.end();

Run the client.js from a different command terminal excluding server.js to see the result -

$ node client.js

Output

Verify the output.

<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!
   </body>
</html>

Verify the output at server end.

Server running at http://127.0.0.1:8081/
Request for /index.htm received.


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js Express Framework.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain