Broad Network


Simple Node.js Server for web Development

Web Development Basics with ECMAScript and MySQL – Part 10

Web Development with ECMAScript and MySQL in Node.js

Foreword: In this part of the series, I present to you a node.js server, which can be used to retrieve HTML pages and images from the web server, and also to send emails and handle data for the MySQL database.

By: Chrysanthus Date Published: 17 Jul 2016

Introduction

This is part 10 of my series, Web Development Basics with ECMAScript and MySQL. In this part of the series, I present to you a node.js server, which can be used to retrieve HTML pages and images from the web server, and also to send emails and handle data for the MySQL database. You should have read the previous parts of the series before coming here, as this is the continuation.

Retrieving and Sending Web Pages
A web server to retrieve and send web pages to the client’s browser 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);

The file for this can be called server.js. I explain this in the first part of the series, so I will not explain it here.

Sending Emails (SMTP)
To send email you need to add code to the above server. You need the Mailsend.js module, which actually sends the email. You need to write your own module, which will convert Form data to email data suitable for the Mailsend.js module.

The top of the server file will become:

    const http = require('http');
    const fs = require('fs');
    const fm = require('./Formmail.js');

where Formmail.js is the module you have written to convert Form data suitable for the Mailsend.js module. For simplicity, all the maim modules for this server are in the same directory as server.js.

            var body = [];

            request.on('data', function(chunk)
                {
                    body.push(chunk);
                }).on('end', function()
                {
                    if (url.search(/.*Formmail\.js\s*$/i) != -1)
                        fm.formmail(body, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });

The URL from the client’s browser (HTML Form) will be something like:

    http://www.yoursite.com:8080/Formmail.js

The data that comes to the server arrives in chunks (series segments). All that is collected in the array variable, body, as bytes.

Formmail.js should have the main function,

    Exports.formmail(body. callback)
        {
            //conversion
        }

This is the function that really does the conversion of Form data suitable for the Mailsend.js module.

In the server, this function is called. The first argument is body, the bytes of Form data. The second argument is the definition of a callback function. If there is an error in the Formmail.js module or the Mailsend.js module, this function definition will send the error message to the client; otherwise it will send a positive feedback to the client (browser). Both the error and positive feedback messages are developed in Formmail.js and arrives in this function definition through callback. This function definition is called from Formmail.js (and not server.js).

Dealing with Database
To deal with the MySQL database, the top of the server.js file becomes:

    const http = require('http');
    const fs = require('fs');
    const fm = require('./Formmail.js');
    const login = require('./login.js');

where login.js is a module written by you to interface the database.

The code to add to server.js is:

                    if (url.search(/.*login\.js\s*$/i) != -1)
                        login.login(body, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });

The explanation is similar to the above.

Dealing with Web Page Images
When you type the URL of a web page at the address bar of your browser, the URL arrives at the web server. The URLs of the images in the web page also arrive at the web server.

Assume that the images in your server have the extensions, .gif and .jpg, then, the code to deliver the images is:

                    if (url.search(/.*\.gif\s*$|.*\.jpg\s*$/i) != -1)
                        {
                            fs.readFile(url, (err, data) => {
                                if (err)
                                    throw err;
                                else
                                    {
                                        matchObj = url.match(/\....\s*$/);
                                        matchStr = matchObj.toString();
                                        ext = matchStr.replace(/\s*/g, '');
                                        ext = ext.replace(/\./, '');
                                        contType = 'image/' + ext;
                                        response.setHeader('Content-Type', contType);
                                        response.end(data);
                                    }
                            });
                      }

Note the use of the content-type, 'image/gif' or 'image/jpg' .

Complete Code
A complete code for explanation similar to the above is:

    const http = require('http');
    const fs = require('fs');
    const ms = require('./Mailsend.js');
    const regi = require('./register.js');
    const login = require('./login.js');
    const more = require('./more.js');


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

            const fs = require('fs');

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


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


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

                         output = data.toString('utf8');
                         response.end(output);
                    });
                }


            var body = [];

            request.on('data', function(chunk)
                {
                    body.push(chunk);
                }).on('end', function()
                {
                    if (url.search(/.*register\.js\s*$/i) != -1)
                        regi.register(body, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });
                    if (url.search(/.*login\.js\s*$/i) != -1)
                        login.login(body, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });
                    if (url.search(/.*more\.js/i) != -1)
                        more.more(url, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });
                });
                if (url.search(/.*\.gif\s*$|.*\.jpg\s*$/i) != -1)
                        {
                            fs.readFile(url, (err, data) => {
                                if (err)
                                    throw err;
                                else
                                    {
                                        matchObj = url.match(/\....\s*$/);
                                        matchStr = matchObj.toString();
                                        ext = matchStr.replace(/\s*/g, '');
                                        ext = ext.replace(/\./, '');
                                        contType = 'image/' + ext;
                                        response.setHeader('Content-Type', contType);
                                        response.end(data);
                                    }
                            });
                      }


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

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

        }).listen(8080);

That is it for this part of the series. We continue in the next part.

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

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message