In the section called “Modules in Node.js” we introduced modules with an intention. So, if we promote them, let us use them too.
myg55/main.js
"use strict";
var server = require("./bin/server"); // make server module available
var router = require("./routes/router"); // router module
server.start(router); // start server
// callback to route
myg55/server.js
"use strict";
/*
* new server.js adds request body data
*/
const http = require("http"); // http module
const lib = require("../private/libWebUtil"); // home grown utilities
const hostname = "localhost";
const port = Number(process.argv[2]) || 3000;
module.exports = {
start(router) {
const server = http.createServer();
server.on("request", function (req, res) { // eventhandler for "request"
console.log(lib.makeLogEntry(req)); // home made utility for logging
let body = [];
req.on("data", function (bodyData) { // eventhandling for data reception
body.push(bodyData); // bodyData is an object
});
req.on("end", function () { // eventhandling for end-of-data
body = Buffer.concat(body).toString(); // body2string
router.route(req, res, body); // pass to router
});
});
server.listen(port, hostname, function () {
console.log(`Log: Server started on http://${hostname}:${port}/`);
});
}
}myg55/libWebUtil.js
/* libWebUtil.js Service Module */
"use strict";
const querystring = require("querystring"); // file system access
const getJSONString = function (obj) { // prettyprint obj
return JSON.stringify(obj, null, 4);
}
const makeWebArrays = function (req, data) {
let get = req.url.split("?");
let qs = "";
if (get.length === 2) {
qs = get[1];
}
let GET = querystring.parse(qs);
let POST = querystring.parse(data);
console.log(getJSONString({ GET, POST }));
return { GET, POST };
}
const makeLogEntry = function(req) {
let now = new Date();
let s = "";
let month = now.getMonth() < 10 ? "0" + now.getMonth() : "" + now.getMonth();
let date = now.getDate() < 10 ? "0" + now.getDate() : "" + now.getDate();
let hours = now.getHours() < 10 ? "0" + now.getHours() : "" + now.getHours();
let mins = now.getMinutes() < 10 ? "0" + now.getMinutes() : "" + now.getMinutes();
let secs = now.getSeconds() < 10 ? "0" + now.getSeconds() : "" + now.getSeconds();
s += `${now.getFullYear()}-${month}-${date}`;
s += "T";
s += `${hours}:${mins}:${secs}`;
s += " ";
s += `${req.method} ${req.url}`;
return s;
}
exports.makeWebArrays = makeWebArrays;
exports.makeLogEntry = makeLogEntry;
myg55/router.js
"use strict";
/*
* check if routed handler function exists
* if yes call it, else complain
*/
const handlers = require("./handlers"); // handlers module
const requestHandlers = { // application urls here
"/home": handlers.home,
"/info": handlers.info,
"/contact": handlers.contact,
"/about": handlers.about,
"/hello": handlers.hello,
"/notfound": handlers.notfound,
}
module.exports = {
route(req, res, body) {
if (typeof requestHandlers[req.url] === 'function') { // look for route
requestHandlers[req.url](req, res); // if found use it
} else {
requestHandlers["/notfound"](req, res); // use notfound
}
}
}
myg55/handlers.js
'use strict';
/*
* handlers.js
* Requesthandlers to be called by the router mechanism
*/
module.exports = {
home(req, res) {
res.end("<h1>Front Page</h1>");
},
info(req, res) {
res.end("<h1>Info Page</h1>");
},
contact(req, res) {
res.end("<h1>Contact Us at:</h1>");
},
about(req, res) {
res.end("<h1>Learn About Us</h1>");
},
hello(req, res) {
res.end("<h1>Send Us an Email</h1>");
},
notfound(req, res) {
console.log(`Log: No handler found for route ${req.url}.`);
res.end();
}
}
On your CLI do npm test to start the server.
Then go to your browser and test each of the following
urls. Be sure to check the log too.
Check the browser screen as well as the console log in each case.