Broad Network


Introduction to Node Web Server

Web Development Basics with ECMAScript and MySQL in Node.js – Part 1

Web Development with ECMAScript and MySQL in Node.js

Foreword: In this part of the series, I explain how to set up a node web server.

By: Chrysanthus Date Published: 16 Jul 2016

Introduction

This is part 1 of my series, Web Development Basics with ECMAScript and MySQL in Node.js. In this part of the series, I explain how to set up a node web server.

Pre-Knowledge
You should have professional knowledge in website design and ECMAScript before coming here, to better understand this series.

A Web Server
The Internet is a network of computers. In some of the computers you have software called the web server. Many of the computers in the Internet are called client computers, and each client has a web browser. A client uses the browser to make a request to the web server; the web server responds.

The request may ask for a web page, for example. The request may ask for information from a database associated with the web server. The request may ask the server to send an email to an email server (in some other computer). The request may ask for some other information from the web server.

Some requests need responses back to the client and others do not. If a response is needed, the web server has the duty to respond (for example, send a web page to the client’s browser).

A Node Web Server
A node server is a web server that you the programmer (web designer or web developer) designs. You actually have to create the server. It is not as difficult as it seems. A web server can be big or small. In this series I show you how to create a small web server (a small node server).

Port
Any application (program) in a computer in the Internet (network), has two important figures associated with it. One called the IP address or domain name identifies the computer in the network. The other called the port, identifies the application in the computer. A port is a number. The default port for a web server is port 80. It is supposed to be typed in the address bar of the browser when requesting a web page. It is usually not typed because it is the default number, and most web servers use it.  However, in this series, you will use port (number) 8080.

In order for a server to receive a request, it has to be listening (waiting for) to requests at its port (8080).

Object
An object is a special kind of code in the memory of the computer.

Main Components of a Node Web Server
A node server has three main objects (in memory), which are the server object, request object and the response object. The server object on its own cannot do anything. It has to work with the request and response objects.

When a request from the browser reaches the server, it is the request object that handles the request. If there is any response (feedback to client), it is the response object that handles that.

Coding
A node server is created in a single text file. It is not long.

Loading the HTTP Module
A module is a file containing commonly used functions. It may have some variables. It may also have some ECMAScript objects and classes. The Node.js installation comes with a built-in module called, http. The functions to create the server and the request and response objects are in this module. To load this module into memory, type the following statement in the file (script) that creates the server:

    var http = require('http');

Here, http is a variable name of your choice (you can give it a different name if you want to). 'http' should be typed as is. It is the argument to the predefined ECMAScript function, require(). It identifies the module. The require() function loads the module. The require() function loads the module and returns the an object called, the http object. This object is held by the variable (name of your choice), http.

Creating the Server
The skeleton statement to create the server is:

    var server = http.createServer();

Here, server is the name of your choice. http is the object returned by the “require('http')” expression above. http has the method, createServer(). This method creates the server and returns the server object, held by the variable, server.

An anonymous function is a function without a name. The main argument to the createServer() method is the anonymous function:

    function(request, response)
        {
            // your statements go here
        }

Now, when the http module is required (imported), it comes with the request and response objects. The request object is identified by request, and the response object is identified by response. These identifiers are the two arguments to the anonymous function.

So, the statement to create the server should be:

var server = http.createServer(function(request, response)
        {
            // your statements go here
        });

Here, we have an anonymous function with two arguments (two objects) and the create-server method with one argument, which is the anonymous function.

Listening
Now, “http.createServer()” is the server object. So it can be followed by a dot and a method. The object has a method called, listen. This is the method that listens for a request (at port 8080). So the create-server statement would be:

    var server = http.createServer(function(request, response)
        {
            // your statements go here
        }).listen(8080);

or

    http.createServer(function(request, response)
        {
            // your statements go here
        }).listen(8080);

if you do not want to hold the return server reference (object).

Handling Request

URL
Note: the request object is an instance of incoming message. The request object has a data property called, url. This property returns the full URL without the server, protocol or port. For a typical URL, this means everything after and including the third forward slash, e.g. /dir1/dir2/file.htm.

If this value is '/', it means the home page is requested. If the value ends with .htm or .html, it means a web page for the path is requested. You can obtain the URL in your script as follows:

    var url = request.url;

The following code segment is for the home page (index.htm) URL:

            if (url == '/')
                url = '/server/index.htm';

This assumes that index.htm is in the directory, c:/server

The following code will indicate whether the url is for an html file:

            if (url.search(/.*\.htm\s*|.*\.html\s*/i) != -1)    //regular expression
                {
                    //retrieve the file
                }

Reading a File
Whether the home page is requested or an HTML file in a sub directory to the home page is requested, you need to read the file. The code to read the file, products.htm in the directory, dir1/dir2/products.htm, is as follows:

    const fs = require('fs');

    fs.readFile('/dir1/dir2/products.htm', (err, data) => {
        //process file read
    });

The first forward slash in the directory path indicates the root directory (c:/).

The first statement brings in (loads) a module called the File System module. The expression returns an object, which can be used to read files and also write to files. One of the methods of this object is readFile(). The method takes two arguments. The first argument is the path to the file including the filename. The second argument is an anonymous function.

In this anonymous function, the reserved word, function, is not used. Instead it begins with a grouping element with two identifiers. Then you have the => punctuator and then the function body in curly brackets. These two identifiers are variables for the readFile() method: the first receives the error message if any error occurs from the readFile() method; the second receives the content of the file read. The purpose of the body of the anonymous function is to process the output of the readFile() method

In the course of reading, an error may occur (the file may not be readable). So, the above code should be:

    const fs = require('fs');

    fs.readFile('/dir1/dir2/products.htm', (err, data) => {
        if (err) throw err;
        output = data.toString('utf8');
    });

data is not a string; it is what is known as a buffer. It has to be converted to a string with “toString('utf8')”. output is the content of the file.

On Error
The request object has a method called, on. This method listens for an error that may occur while the request object is processing the request. You must code this method (otherwise your server will crash for certain errors). The code is:

    request.on('error', function(err)
        {
            // print error to output
        });

The on method has two arguments. The first argument has to be 'error'. The second argument is an anonymous function with the “function” reserved word. Its argument, err receives the error. err is an error object. The body of the anonymous function prints the error.

So far, the server code for handling requests can be something like:

    var http = require('http');

    http.createServer(function(request, response)
        {
            var url = request.url;

            const fs = require('fs');

            fs.readFile('/dir1/dir2/products.htm', (err, data) => {
                    if (err) throw err;
                    output = data.toString('utf8');
                });

            request.on('error', function(err)
                {
                    // print error to output
                });

        }).listen(8080);

Handling Response

Response Header
Now, before data is sent back to the client, it must be preceded by another short data called the header. The response object sends this header. You, the programmer, has to set this header for the response object. In the case of a web page, the header is “'Content-Type', 'text/html'”. You set this header for the response object, using the response setHeader property (method), as follows:

    response.setHeader('Content-Type', 'text/html');

Sending File Content back to Client
Assume that the request asked for a web page, and the web page has been read and the content is in the ECMAScript variable (identifier), data. To send this content to the client, the statement is:

    response.end(data);

The response object has a property (method) called, end(), which can be used for this.

On Error
An error can also occur during the response process. The code to handle this is:

    response.on('error', function(err)
        {
            //send error message to output
        });

Complete Code
The complete code for the very simple node server, and its request and response object, is:

    const http = require('http');

    http.createServer(function(request, response)
        {
            var url = request.url;

            const fs = require('fs');

            if (url == '/')
                url = '/server/index.htm';
            else
             url = '/server' + url;

            if (url.search(/.*\.htm\s*|.*\.html\s*/i) != -1)
                 {
                     fs.readFile(url, (err, data) => {
                         if (err) throw err;

                         output = data.toString('utf8');
                         response.setHeader('Content-Type', 'text/html');
                         response.end(output);
                    });
                }

            request.on('error', function(err)
                {
                    // print error to output
                });

            response.on('error', function(err)
                {
                    //send error message to output
                });

        }).listen(8080);

Note that the response handling has been placed inside the readFile() method.

Downloading and Installation
Node.js is a library that can be used to create a web server. You use ECMAScript as the programming language. In this section I tell you what I did to download and install Node.js. You should do a similar thing for your computer. I am using the Windows Operating System.

I used my browser to go to the site, https://nodejs.org. From there, I downloaded Node.js v4.4.2 installation file. The name of the installation file is, node-v4.4.2-x86.msi. In my computer, I double-clicked the file and I allowed the default settings.

Testing the Server
Create a directory called, server in the root directory (drive C:\) of your computer. Copy the complete code above into a text editor file. Save the file in the directory created with the name, server.js .

Create the following HTML file and save it with the name index.htm in the server directory:

<!DOCTYPE HTML>
<html>
<head>
    <title>Home</title>
</head>
<body>
    Home Page
</body>
</html>

Create the following two directories in the server directory:

    dir1/dir2

Create the following HTML file and save it with the name temp.htm in the c:/server/dir1/dir2 directory:

<!DOCTYPE HTML>
<html>
<head>
    <title>A Page</title>
</head>
<body>
    Just a Web Page
</body>
</html>

All the testing is taking place in the same computer. The server code will still work in the same way if it was in a different computer.

To run the server, open the Command Prompt Window (console). Go to the root directory (cd c:\). Type the following command:

    node server/server.js

where, node is the node.js interpreter. server is the server directory and server.js is the server script.

Shortly after pressing the Enter Key, you should see an underscore flashing. This means the server is running. Such a server (program) can only be stopped using the operating system (closing the Prompt window) or by shutting down the computer.

Now, if the node server is running, open your browser window (using the operating system).

In the address bar of the browser, type,

    localhost:8080

and click Go.

The home page should open at your browser.

In the address bar of the browser again, type,

    localhost:8080/dir1/dir2/temp.htm

and click Go.

You should see the content of the temp.htm web page.

At this point, you should know how to set up a minimum web server using node.js.

Let us take a break here and continue in the next part of the series.

Chrys

Related Links

Web Development Basics with ECMAScript and MySQL
ECMAScript Validation of HTML Form Data
Web Live Text Chart Application using ECMAScript and MySQL
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

NEXT

Comments

Become the Writer's Follower
Send the Writer a Message