Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have this lab that needs to log all client access requests to a text file. I got the moments up and running and is

I have this lab that needs to log all client access requests to a text file. I got the moments up and running and is correct but now we have to do the lab with connect and serve-static modules.Here is what is needed for this lab. Any help and understanding would be appreciated.

Your job is to modify app.js file in this project so that your Node.js web server will log all client access requests to a text file called access.log. The format of the log file is:

datetime | user-agent | browser language | original url requested

Here are some sample log entries from access.log file:

Mon Jul 18 2016 15:46:24 GMT-0400 (Eastern Daylight Time)|Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36|en-US,en;q=0.8,es;q=0.6|/

Mon Jul 18 2016 15:47:12 GMT-0400 (Eastern Daylight Time)|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko|en-US,es;q=0.8,zh-CN;q=0.5,en;q=0.3|/images/career.jpg

Mon Jul 18 2016 15:46:47 GMT-0400 (Eastern Daylight Time)|Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0|en-US,en;q=0.5|/css/interface.css

The above entries show three access attempts to our web site. The first one is from a Chrome browser which accepts only en-US and en languages. The requested URL is /. The second one is from an IE browser which accepts en-US, es, and zh-CN languages. The requested URL is /images/career.jps. The last one is from a FireFox browser which accepts en-US and en languages. The requested URL is /css/interface.css.

We can write a small program to analyze this log file and show the daily hits of each page of our web site. We can also tally the most popular browsers used to access our web site.

You need to submit only the modified app.js file.

Hint:

1. You need to require the fs module and create a file write stream to write the log to access.log.

Example: var ws = fs.createWriteStream(access.log, {flags: a}); //append

2. You can re-use the existing custom middleware called logit or create a new one.

3. You can get user agent, browser language and requested URL by doing this:

var reqHeader = req.headers;

var userAgent = reqHeader[user-agent];

var browserLanguage = reqHeader[accept-language];

var requestedUrl = req.originalUrl;

Here is the app.js for this lab

/**  app.js  This is a simple web site that hosts  a fake Wake Tech Credit Union web site.  It uses the third-party module: connect version 3.4.1.  and serve-static version 1.11.1  For detailed information on connect module  visit its official NPM web site at:  https://www.npmjs.com/package/connect  */  var connect = require('connect'); var http = require('http'); var serveStatic = require('serve-static'); var util = require('util'); // Create an app var app = connect(); // Create a middleware that serves static web pages using third-party module: static-serve var staticMiddleware = serveStatic('public', {index:['index.html', 'index.htm']}); // Create a custom access log middleware to the console function logit(req, res, next) { util.log(util.format('Request received: %s, %s', req.method, req.url)); next(); } // Mount all the middlewares app.use(logit).use(staticMiddleware).listen(3333); console.log('static web server started on port 3333'); This is the app.js for the last lab that is running
/** app.js This is a simple web site that hosts a fake Wake Tech Credit Union web site. It is used to demonstrate how easy it is to create and deploy a web sever using Node.js. */  var express = require('express'); //dowmload moments from npm var moment = require('moment'); var fs = require('fs'); /**  * Define the sample application.  */ var SampleApp = function() { // Scope.  var self = this; /* ================================================================ */  /* Helper functions. */  /* ================================================================ */   /**  * Set up server IP address and port # using env variables/defaults.  */  self.setupVariables = function() { // Set the environment variables we need.  //self.ipaddress = process.env.IP;  //self.port = process.env.PORT || 5000;   //if (typeof self.ipaddress === "undefined") {  // self.ipaddress = "127.0.0.1";  //};  }; /**  * Populate the cache.  */  self.populateCache = function() { if (typeof self.zcache === "undefined") { self.zcache = { 'index.html': '' }; } // Local cache for static content.  self.zcache['index.html'] = fs.readFileSync('./index.html'); }; /**  * Retrieve entry (content) from cache.  * @param {string} key Key identifying content to retrieve from cache.  */  self.cache_get = function(key) { return self.zcache[key]; }; /**  * terminator === the termination handler  * Terminate server on receipt of the specified signal.  * @param {string} sig Signal to terminate on.  */  self.terminator = function(sig){ if (typeof sig === "string") { console.log('%s: Received %s - terminating sample app ...', Date(Date.now()), sig); process.exit(1); } console.log('%s: Node server stopped.', Date(Date.now()) ); }; /**  * Setup termination handlers (for exit and a list of signals).  */  self.setupTerminationHandlers = function(){ // Process on exit and signals.  process.on('exit', function() { self.terminator(); }); // Removed 'SIGPIPE' from the list - bugz 852598.  ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'  ].forEach(function(element, index, array) { process.on(element, function() { self.terminator(element); }); }); }; /* ================================================================ */  /* App server functions (main app logic here). */  /* ================================================================ */   /**  * Create the routing table entries + handlers for the application.  */  self.createRoutes = function() { self.routes = { }; //creates two variables for writing to a text file  var myWriteFile = fs.createWriteStream('feedback.log'); var rightNow = moment(); self.routes['/feedback'] = function(req, res) { console.log("-- Received a customer feedback: [" + req.body.feedback + "]"); //prints out feedback from WTCU and writes in on new lines  myWriteFile.write("[" + rightNow.format("MM-DD-YYYY, HH:mm:ss") + "] " + req.body.feedback +" "); res.send("WTCU FeedbackThanks for your feedback!"); }; self.routes['/'] = function(req, res) { res.setHeader('Content-Type', 'text/html'); res.send(self.cache_get('index.html') ); }; }; /**  * Initialize the server (express) and create the routes and register  * the handlers.  */  self.initializeServer = function() { self.createRoutes(); //self.app = express.createServer();  self.app = express(); self.app.set('port', process.env.PORT || 3333); self.app.set('ip', process.env.IP || "127.0.0.1"); self.app.use(express.static(__dirname)); //self.app.use(express.bodyParser());  self.app.use(express.json()); self.app.use(express.urlencoded()); // Add handlers for the app (from the routes).  for (var r in self.routes) { self.app.get(r, self.routes[r]); // maps the HTTP GET request  self.app.post(r, self.routes[r]); // maps the HTTP POST request  } }; /**  * Initializes the sample application.  */  self.initialize = function() { self.setupVariables(); self.populateCache(); self.setupTerminationHandlers(); // Create the express server and routes.  self.initializeServer(); }; /**  * Start the server (starts up the sample application).  */  self.start = function() { // Start the app on the specific interface (and port).  self.app.listen(self.app.get('port'), function() { console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), self.app.get('ip'), self.app.get('port')); }); }; }; /* Sample Application. */  /**  * main(): Main code.  */ var zapp = new SampleApp(); zapp.initialize(); zapp.start(); 

Any kind of help or feedback would be great.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

DB2 Universal Database V7.1 Application Development Certification Guide

Authors: Steve Sanyal, David Martineau, Kevin Gashyna, Michael Kyprianou

1st Edition

0130913677, 978-0130913678

More Books

Students also viewed these Databases questions

Question

Explain exothermic and endothermic reactions with examples

Answered: 1 week ago