DotNetCurry Logo

Using Node.js to read HTML file and send HTML response

Posted by: Mahesh Sabnis , on 4/4/2016, in Category Node.js
Views: 17883
Abstract: Read HTML file in Node.js using simple File IO operations and send a HTML response back to client.

In traditional web applications, a web server (e.g. IIS) contains the directory structure to manage web pages (html, asp, aspx, etc.). When a request for the page is received, the web server performs the request processing based upon server-side configuration and returns the matching HTML response. This configuration contains information for the page extension and its associated runtime. This is because the hosting environment needs the complete information about the page from the URL, and then accordingly it discovers the page on the server.

 

In Node.js we can perform these operations using the File Module (fs) and the http module.

Node.js scans the URL based on which it reads the corresponding html file and responds to the request message. In this article, we will create a Node.js project with a HTML file in it. Our code will then read the request URL and based on it, the response will be sent back.

Prerequisites for the implementation.

To implement following steps we need resources as listed below:

Visual Studio Code or Visual Studio 2013/2015

Node Tools for Visual Studio

 

Implementation

The implementation here uses Visual Studio Code. This a free IDE for building and debugging modern web and cloud applications on the Windows, Mac OSX and Linux platform.

Step 1: Create a folder on the drive (e.g. E:\) of name VSCoderespondHtml. In this folder add a new folder of the name Scripts. We will be using this to store our application files. Open Visual Studio Code. Open the VSCoderespondHtml folder using File > Open Folder Option. Once the folder is opened, the option for creating a new file will be displayed to the right, as shown in the following image. Select the Script folder and click on the new file icon as shown in the following image. This will provide a blank textbox where you create a new file name as app.js.

new-nodejs-file

Step 2: In the VSCoderespondHtml folder, add a folder of name AppPages. In this folder add a new HTML file of name MyPage.html. Add the following markup in it:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>The Page Returned by Making Http Call to Node.js</title>
    <style type="text/css">
        table, td {
          border:double;
        }
    </style>
</head>
<body>
    <h1>Product Information Page</h1>
    <table>
        <tr>
            <td>Product Id:</td>
            <td>
                <input type="text" />
            </td>
        </tr>
        <tr>
            <td>Product Name:</td>
            <td>
                <input type="text" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="button"  value="Save"/>
            </td>
        </tr>
    </table>


</body>
</html>

This is a simple HTML file which will be sent with the request.

Step 3: Open app.js and add the following code in it

//1.
var http = require('http');
var fs = require('fs');
//2.
var server = http.createServer(function (req, resp) {
    //3.
    if (req.url === "/create") {
        fs.readFile("AppPages/MyPage.html", function (error, pgResp) {
            if (error) {
                resp.writeHead(404);
                resp.write('Contents you are looking are Not Found');
            } else {
                resp.writeHead(200, { 'Content-Type': 'text/html' });
                resp.write(pgResp);
            }
            
            resp.end();
        });
    } else {
        //4.
        resp.writeHead(200, { 'Content-Type': 'text/html' });
        resp.write('<h1>Product Manaager</h1><br /><br />To create product please enter: ' + req.url);
        resp.end();
    }
});
//5.
server.listen(5050);

console.log('Server Started listening on 5050');

The above code performs the following operations. (Note: Comments on each line match with the numbers used in the following points.)

1. Since we need to create web server for http messaging, we need http module. We will be reading the html file using File IO, for that we need to load fs module.

2. Create an http server with the callback for request processing.

3. If the URL contains ‘/create’ value in it, the MyPage.html file will be read. If the file is not read successfully, the response with Http Status as Not Found will be sent for the request message. If the file is read, then the html response will be sent back.

4. If the URL does not match with ‘/create’, then default Html message will be sent back for the request.

5. The server will start listening on port 5050.

 

Step 4: Right-Click on the app.js and select Open in Command Prompt option. This will show the command prompt from where we can run the application.

nodejs-command-prompt

On this command enter the following Command

Node app

The following result will be displayed

cmd-exe

Step 5: Open any browser and enter the following URL

http://localhost:5050

The following result will be displayed

product-manager

This is the default response we have received. But we need a HTML response, to receive it, change the URL as following

http://localhost:5050/create

 

response-html

Now we have received the html page successfully.

Conclusion: With simple File IO operations we can read HTML file in Node.js and by using simple modules, we can send a HTML response back to client.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!