Node.js

Assignments From Chapter 26

Assignments Node II

Assignment Node II.0

Using your own version of the lesson's myg52/main.js You should submit something like http://localhost:3000/test.html?name=Niels&position=Lecturer&height=183 to the started server.

Do the same experiment with different URL lines from your browser. Try varying the test.html to something else, and try varying the query string too.

Check the log of the server and write briefly an explanation to the output.

Solution Assignment Node II.0
Example B.87. The Server Start Up File - assII/run.js
'use strict';
var server = require("./server");   // local module server available
var router = require("./router");   // router module

server.start(router.route);         // to router

Example B.88. The Server Module - assII/server.js
'use strict';
const http = require('http');           // http module
const url = require('url');             // provides access to url object
const path = require("path");           // object for path manipulation
const fs = require("fs");               // access to filesystem

const hostname = 'localhost';
const port = Number(process.argv[2]) || 3000;

module.exports = {
    start(route) {
        const server = http.createServer((req, res) => {
            let parsed = url.parse(req.url).pathname;
            console.log(`Request url: ${parsed}`);
            if (path.extname(parsed) === '')
                parsed = patch_filename(parsed);
            let type = path.extname(parsed).substring(1);   // drops '.'
            route(parsed, type, res);   // defer action to router
        });
        server.listen(port, hostname, () => {
            console.log(`Server started. Navigate to http://${hostname}:${port}/ to use it.`);
        });
    }
}

const directory_index = ['index.html', 'index.xhtml'];

function patch_filename(path) {
    if (path[path.length-1] != "/") {
        path += "/";
    }
    let filename = path;
    for (let i = 0; i < directory_index.length; i++) {
        filename += directory_index[i];
        fs.access("." + filename, fs.F_OK, function(err) {
            if (err) {
                console.error(err)
                filename = path;
            }
        });
        break;
    }
    if (filename === path)
        return "";
    return filename;
}

Example B.89. The Router Module - assII/router.js
'use strict';
/*
 * check if handler function exists and if yes call it, else complain
 */
const directoryIndex = {};
const requestHandlers = require("./requestHandlers");

const handlers = {
    "/": requestHandlers.start,
    "css": requestHandlers.css,
    "htm": requestHandlers.html,
    "html": requestHandlers.html,
    "xhtml": requestHandlers.html,
    "jpg": requestHandlers.jpg,
    "js": requestHandlers.js,
    "mov": requestHandlers.mov,
    "/notFound": requestHandlers.notFound,
    "/upload": requestHandlers.upload

};

module.exports = {
    route(path, type, resp) {
		if (typeof handlers[path] === 'function') {
            handlers[path](resp);
        } else if (typeof handlers[type] === 'function') {
	            handlers[type](resp, path);
        } else {
        	handlers['/notFound'](resp);
        }
    }
}

Example B.90. The Requesthandlers Module - assII/requestHandlers.js
'use strict';
/*
 * requestHandlers.js
 */
const exec = require("child_process").exec;
const fs = require('fs');

const error404 = function(res) {
    res.writeHead(404, {"Content-Type": "text/html"});
    res.write("<h3>File or handler not found</h3>");
    res.end();
}

module.exports = {

    notFound(res) {
        console.log("Handler 'notFound' was called.");
                                    // what 'start' is supposed to deliver
        error404(res);
    },

    start(res) {
        console.log("Handler 'start' was called.");
                                    // what 'start' is supposed to deliver
        exec("ls -al", function (error, stdout, stderr) {
            if (error)
                error404(res);
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.write(stdout);
            res.end();
        });
    },

    upload(res) {
        console.log("Handler 'upload' was called.");
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.write("Hello from Upload handler");
        res.end();
    },

    html(res, path) {
        console.log("Handler 'html' was called.");
        fs.readFile('.' + path, (error, pgResp) => {   // read from fs
            if (error) {
                error404(res);
            } else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write(pgResp);
                res.end();
            }
        });
    },

    jpg(res, path) {
        console.log("Handler 'jpg' was called.");
        fs.readFile('.' + path, (error, pgResp) => {   // read from fs
            if (error) {
                error404(res);
            } else {
                res.writeHead(200, { 'Content-Type': 'text/jpeg' });
                res.write(pgResp);
                res.end();
            }
        });
    },

    js(res, path) {
        console.log("Handler 'js' was called.");
        fs.readFile('.' + path, (error, pgResp) => {   // read from fs
            if (error) {
                error404(res);
            } else {
                res.writeHead(200, { 'Content-Type': 'text/js' });
                res.write(pgResp);
                res.end();
            }
        });
    },

    css(res, path) {
        console.log("Handler 'css' was called.");
        fs.readFile('.' + path, (error, pgResp) => {   // read from fs
            if (error) {
                error404(res);
            } else {
                res.writeHead(200, { 'Content-Type': 'text/css' });
                res.write(pgResp);
                res.end();
            }
        });
    }
}

Example B.91. The Front Page - assII/index.html
<!doctype html>
<html>
    <head>
        <title>Server Front Page</title>
        <meta charset='utf-8'/>
        <link rel="stylesheet" href="/site1/css/mystyles.css"/>
    </head>
    <body>
        <header>
            <h1>Server Front Page</h1>
            <nav>
                <ul>
                    <li><a href='/index.html'>Home</a></li>
                    <li><a href='/site1/index.html'>Page1</a></li>
                </ul>
            </nav>
        </header>
    </body>
</html>

Example B.92. The Interesting Page - assII/site1/index.html
<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8'/>
        <title>Assignment assII</title>
        <link rel="stylesheet" href="/site1/css/mystyles.css"/>
        <script src="./js/nQuery.js"></script>
    </head>
    <body>
        <header>
            <h1>Node.js at Your AssII Service</h1>
            <nav>
                <ul>
                    <li><a href='/index.html'>Home</a></li>
                    <li><a href='/site1/index.html'>Page1</a></li>
                </ul>
            </nav>
        </header>
        <div><img src='./images/parkencrop.jpg' alt='parkencrop'/></div>
        <p>Lorem ipsum? Really?</p>
        <div><img id='iot' src='http://x15.dk/prez/iothings/geekandpokeIOT.jpg' alt='geekandpokeIOT'/></div>
    </body>
</html>