Node.JS - Web Server - Day Eight

Web Server is an application software, which is used to handle the request generated by the client, using HTTP protocol. In Node.js, HTTP Server is a zero configuration Command Line HTTP Server. In this article, we learn how to configure a Node.js HTTP Server. Let’s take a simple example then move to some complex examples.
 
Example:
  1. var http = require('http');  
  2. //Create a Event Listener  
  3. http.createServer(function (request, response) {  
  4. //Write Header for resposne  
  5. response.writeHead(200, { 'Content-Type''text/plain' });  
  6. response.end('This is HTTP Server Example\n');  
  7. }).listen(1400, '127.0.0.1');  
In the code mentioned above, we use ‘http’ module, which uses require function. We use the “createServer” function of http module, which will create HTTP Server. In callback function, we take two parameters' request and response. Request method defines the request. In response parameter, we write the header information, where we will define the header of the data or information sent in form of response and “end” method indicates that it is end of the data. At last, we use the “listen” method, which defines the port number and IP address for HTTP Server.
 
Now, run the program and open “localhost:1400” address in your Browser.
 
 
 
When you inspect the element and go to the Network tab, you will find the information given below.
 
 
 
You can see that status code is “200” and Content type is “text/plain”, which we defined in our program. When you open Response tab, it will show the data that it gets in the form of response from the Server.
 
 
 
Plain text mentioned above is the text which we defined in response to the created Server.
 
Send HTML content
 
In the previous example, we send the plain text. Now, we learn how to send HTML data to the response of request. First, create HTML file named as “index.html” and insert some data into the file.
 
Content
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <style>  
  5.         table {  
  6.             font-family: arial, sans-serif;  
  7.             border-collapse: collapse;  
  8.             width: 100%;  
  9.         }  
  10.   
  11.         td, th {  
  12.             border: 1px solid #dddddd;  
  13.             text-align: left;  
  14.             padding: 8px;  
  15.         }  
  16.   
  17.         tr:nth-child(even) {  
  18.             background-color: #dddddd;  
  19.         }  
  20.     </style>  
  21. </head>  
  22. <body>  
  23.   
  24.     <table>  
  25.         <tr>  
  26.             <th>Company</th>  
  27.             <th>Contact</th>  
  28.             <th>Country</th>  
  29.         </tr>  
  30.         <tr>  
  31.             <td>Pankaj</td>  
  32.             <td>1234567890</td>  
  33.             <td>India</td>  
  34.         </tr>  
  35.         <tr>  
  36.             <td>Rahul</td>  
  37.             <td>2345678910</td>  
  38.             <td>Mexico</td>  
  39.         </tr>  
  40.         <tr>  
  41.             <td>Sandeep</td>  
  42.             <td>6541230789</td>  
  43.             <td>Austria</td>  
  44.         </tr>  
  45.         <tr>  
  46.             <td>Sanjeev</td>  
  47.             <td>231459870</td>  
  48.             <td>UK</td>  
  49.         </tr>  
  50.          
  51.     </table>  
  52.   
  53. </body>  
  54. </html>  
App.js File
  1. var http = require('http');  
  2. var fs = require('fs');  
  3. //Create a Event Listener  
  4. http.createServer(function (request, response) {  
  5.     //Write Header for resposne  
  6.     response.writeHead(200, { 'Content-Type''text/html' });  
  7.     fs.readFile(__dirname+'/index.html', function (err, data) {  
  8.         if (err) {  
  9.             console.log(err);  
  10.               
  11.             response.writeHead(404, { 'Content-Type''text/html' });  
  12.         } else {  
  13.               
  14.             response.writeHead(200, { 'Content-Type''text/html' });  
  15.   
  16.               
  17.             response.write(data.toString());  
  18.         }  
  19.         
  20.         response.end();  
  21.     });  
  22. }).listen(1400, '127.0.0.1');    
In this example, we read the data from “index.html” file, using “readFile” method of “fs” module and write down all the data in HTTP response body.
 
Let’s run the code and check the Browser.
 
 
 
You can see that we get HTML formatted data from the Server, which we specified in our index.html file.
 
Use File Stream to Improve the Performance
 
In previous example, we read the data from “index.html” file in synchronous mode, which means when any client generates the request, the Server will try to read and return the whole data in single try, if our data is small and traffic on the Website is not large then this method is OK but in case of large data or huge traffic, this method can generate performance issues. To overcome all these performance issues, we use the “createReadStream” to improve the performance of the our Node.js project. This method allows us to open up a readable stream in a very simple manner and createReadStream method takes the file path to stream. It returns the streamed data to the client.
 
Example:
  1. var http = require('http');  
  2. var fs = require('fs');  
  3.   
  4. http.createServer(function (req, res) {  
  5.     // The filename is simple the local directory and tacks on the requested url  
  6.     var filename = __dirname + '\\index.html';  
  7.   
  8.       
  9.     var readStream = fs.createReadStream(filename);  
  10.   
  11.     res.writeHead(200, { 'Content-Type''text/html' });  
  12.     readStream.on('open', function () {  
  13.           
  14.         readStream.pipe(res);  
  15.     });  
  16.   
  17.       
  18.     readStream.on('error', function (err) {  
  19.         res.end(err);  
  20.     });  
  21. }).listen(1400,'127.0.0.1');  
Output
 
 
 
In this example, we open the file as a readable stream and just write the read stream to response object.
 
JSON Data
 
So far, we return simple text and HTML data as the response of request. In the same manner, we can return JSON data. JSON is the most important format of Node.JS because in Node.js, the data is transferred in form of JSON. Let’s take a simple example of JSON formatted data.
 
Example
  1. var http = require('http');  
  2. var fs = require('fs');  
  3.   
  4. http.createServer(function (req, res) {  
  5.       
  6.     var obj = {  
  7.         name: "Pankaj Choudhary",  
  8.         city: "Alwar",  
  9.         state:"Rajastahn",  
  10.         age: 22  
  11.   
  12.     }  
  13.   
  14.     res.writeHead(200, { 'Comtent-Type''application/json' });  
  15.     res.end(JSON.stringify(obj));  
  16. }).listen(1400,'127.0.0.1');  
Output
 
 
Routing
 
Routing is the process of mapping the data as per HTTP request. In previous example, we returned HTML, text or JSON data regardless of the HTTP . In previous example, we returned JSON data for the “localhost:1400” URL, if you pass http://localhost:1400/demo.html or http://localhost:1400/test.html or another URL then you get the same data but in Routing, we map HTTP request to the content and return the data according to HTTP request.
 
Example
  1. var http = require('http');  
  2. var fs = require('fs');  
  3. http.createServer(function (req, res) {  
  4.     if (req.url == '/') {  
  5.         var filename = __dirname + '\\index.html';  
  6.         var readStream = fs.createReadStream(filename);  
  7.         res.writeHead(200, { 'Content-Type''text/html' });  
  8.         readStream.on('open', function () {  
  9.             readStream.pipe(res);  
  10.         });  
  11.         readStream.on('error', function (err) {  
  12.             res.end(err);  
  13.         });  
  14.     }  
  15.     else if (req.url == '/api/pankaj') {  
  16.         var obj = {  
  17.             name: "Pankaj Choudhary",  
  18.             city: "Alwar",  
  19.             state: "Rajastahn",  
  20.             age: 22  
  21.         }  
  22.         res.writeHead(200, { 'Comtent-Type''application/json' });  
  23.         res.end(JSON.stringify(obj));  
  24.     }  
  25.     else if (req.url == '/api/sandeep') {  
  26.         var obj = {  
  27.             name: "Sandeep Jangid",  
  28.             city: "Gurgaon",  
  29.             state: "Haryana",  
  30.             age: 23  
  31.         }  
  32.         res.writeHead(200, { 'Comtent-Type''application/json' });  
  33.         res.end(JSON.stringify(obj));  
  34.     }  
  35.     else {  
  36.         res.writeHead(200, { 'Comtent-Type''application/text' });  
  37.         res.end("404 error! No page Found");  
  38.     }  
  39.       
  40. }).listen(1400,'127.0.0.1');  
Output
 
In the example mentioned above, we perform the routing and return the result according to the URL parameter values.
 
 
 
 
 
 
 
 
Web Client
 
In the previous example, we created the Web Servers. Now, we create a Web client and send the request to Web Server, which we created in previous example. Create a new Node.js project and save the code, mentioned below in JS file.
 
Code
  1. var http = require('http');  
  2.   
  3. // Set  name, port and path for request to server  
  4. var options = {  
  5.     host: 'localhost',  
  6.     port: '1400',  
  7.     path: '/'  
  8. };  
  9.   
  10. // Callback function is used to deal with response  
  11. var callback = function (response) {  
  12.     // Continuously update stream with data  
  13.     var body = '';  
  14.     response.on('data', function (data) {  
  15.         body += data;  
  16.     });  
  17.   
  18.     response.on('end', function () {  
  19.         // Data received completely.  
  20.         console.log(body);  
  21.     });  
  22. }  
  23. // Make a request to the server  
  24. var req = http.request(options, callback);  
  25. req.end();  
In the example mentioned above, we create a Web client, define the Server name, path and port names in “options” variable. We define the callback function, which will return the data returned from the Server, if request executes successfully. At the end of the code, we send the request to the Server. Now, run the code mentioned above. When you run this code, you will text formatted data written in index.html file.
 
 
 
If you define ‘/api/pankaj’ for the path, you will get the data shown below.
 
 
 
If you define ‘/api/sandeep for the path, you will get the data shown below.
 
 
 
Conclusion
 
In this article, we learned how to create a Web Server in Node.js. In the next article, we will learn about the Express.js, which is actually used to create a Web Server for Node.js Web Applications. Thanks for reading this article.

Up Next
    Ebook Download
    View all
    Learn
    View all