5.1. 5.2. 6.2. 6. Create a Node.js Server 6.1. Invoke the createServer method using your http...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
5.1. 5.2. 6.2. 6. Create a Node.js Server 6.1. Invoke the createServer method using your http object. It requires a callback method as an argument. Use method name processServer Request (you will create the method shortly). Store the reference in a new global variable named httpServer. Start the server by invoking its listen method. Configure the server to listen on port 8080. Declare a new object named eventEmitter. Instantiate event Emitter by calling the EventEmitter constructor from within the events object. Assign an event handler to an event by invoking the on method of the event Emitter object. Pass it two arguments: 1) the name of the event, processing Finished, 2) reference to the event handler function, processing FinishedHandler (you will write this method shortly). 7. Implement the method to process HTTP requests. Function Name: processServerRequest Parameters: two: request and response Return value: none Purpose: This method will process HTTP requests. 7.2. The following parts are the body of the method. 7.1. Store the response object received as a parameter in the global variable, res. This will allow you to access the response object in other methods! 7.3. Create the response header by invoking the writeHead method of the response object. Send an OK status code and Content-Type of text/html as arguments. Ensure that you are using the JSON name-value structure (there is no array, so there will be no square brackets). Add the following head tag by invoking the write method of the response object. This will configure a blank favorite icon for the webpage and stop repeated requests for the favicon file. If there was no error, Execute the query by invoking the query method of the con object. Pass the sqlquery text as an argument. In addition, the query method expects a callback function as an argument. Pass a reference to the method processResult as the second argument. (You will write the method shortly). Terminate the connection by calling the end method of the con object. 9. Implement the method to process the results of the query. Function Name: processResult Parameters: two: err and result Return value: none Purpose: This method will process the result of the sql query. It will go through the resultset and invoke a method which can process each record of the resultset. It will also fire or emit an event announcing that the processing of the result has finished. The following parts are the body of the method. 9.1. Using an if statement test if there was an error (using the err variable). If there was an error log it to the console and throw the error again, i.e. "throw err;" Iterate through the result object by calling its for Each method. The forEach 9.2. method requires a callback function as an argument. Pass it the printRecord method reference as an argument. The callback method should know how to process/handle one record. You will write the printRecord method shortly. 9.3. Fire the processing Finished event. Call the emit method of the event Emitter object. Pass it the name of the event you want to fire or "emit" as a string. 10. Implement the method to process one record of the resultset. Function Name: printRecord Parameters: one: record Return value: none Purpose: This method will process one record of the sql resultset. For each record, it will construct a paragraph element which contains the first and last names of the customer. The following parts are the body of the method. 10.1. Using string concatenation, append to the existing output variable. Append a new paragraph tag which contains the first_name and last_name attributes of the record. 11. Implement the method, which serves as the event handler for processingFinished event. Function Name: processing FinishedHandler Parameters: none Return value: none Purpose: This method will handle the event processingFinished. Essentially, once processing is finished, it can write to the response object. The following parts are the body of the method. 11.1. Create a response by invoking the write method of the response object. Within the write method, pass the output variable as an argument. 11.2. End the response by invoking the end method of the global res object. There is no need to write any html as arguments! 12. Test your Program 12.1. Open a command prompt or terminal window. 12.1.1 On MacOS, you can easily open a terminal window which is already within the folder. 12.1.2 On Windows, change directory to work in the exercise folder. You can use the cd command and paste the full folder path. 12.2. Type node followed by the name of the js file to run the file. 12.3. Open Chrome and navigate to the local host server using port 8080. If your program works, it should connect to the Node.js script and execute the full script. The Node.js program should then send an HTML response back. You should then see the first and last names of customers within individual paragraph elements. Ideally, you shouldn't see erroneous output since the database and the response code should execute in proper sequence due to the event firing/handling mechanism. Getting an undefined? You may see "undefined" as an output. If you don't initialize the output variable, it is undefined at the start! Getting multiple copies of the same output? The Node.js response object uses a buffer to write to the response stream. If you refresh, Node.js flushes the buffer. That is why if you keep refreshing, output will keep getting added to the page. 7.4. Assign a SQL select statement to your global sqlquery variable. Within the query, select the first 5 records from the customer table and retrieve only the first and last name columns. 7.5. Call the initializeDB () method. You will write it shortly! 8. Implement the method to connect to the database and perform other database tasks Function Name: initializeDB Parameters: none Return value: none Purpose: This function will use the MySQL module to connect to the database, run a query and terminate the connection. 8.1. Declare a variable named connectionString and assign to a JavaScript object. It should have the following name/value pairs. Ensure that you are using the JSON name- value structure (there is no array, so there will be no square brackets). 8.2. 8.3. Name host database user password Value cis425.wpcclasses.com sakila cis425Fall2021 User cis425Fall2021 Log the connection string to the console. Create a connection by invoking the createConnection method of the mysql object. Pass the connectionString to the method as an argument.createConnection will return a reference to the new connection object. Store it in a new variable named con. 8.4. Log that you are going to connect to the database. 8.5. Start the connection by invoking the connect method of the con object. Pass an inline function declaration as an argument. The function should accept one variable, err, as an argument. The following statements are the body of the inline function. The function is anonymous, i.e. it doesn't have a name. 8.6. Use an if statement to test if there was an error (using the err variable). If there was an error, log the error and throw the err object, i.e. "throw err;". Sample Output HTML file, after connecting to localhost localhost:8080 X + localhost:8080 MARY SMITH PATRICIA JOHNSON LINDA WILLIAMS BARBARA JONES ELIZABETH BROWN 2 Overview In this assignment, you will implement a custom event, which will be fired or "emitted" as well as handled by you. The database will be queried and the results output to a webpage. However, the webpage can only be created after the query results are processed. This will be implemented using an event. The processing of the results will be associated with an event. After the event happens, a method will handle it and print the results to a webpage. 1. Create a new Project folder 1.1. Rename the folder for the assignment. Name the folder in the structure asuriteE#, replacing # with the assignment number. 1.2. Create a blank file and name it events.js 2. Install the mysql package using NPM 2.1. Open a command prompt or terminal window and change the directory to your project folder. 2.2. Use npm install mysql to install the mysql package. 3. Setup the files 3.1. Add your name, assignment #, class, and class time as a comment at the top of the both JavaScript file e.g., John Smith, E13, CIS 235,9 am Work on the JavaScript file 4. Create Global Variables 4.1. Import the http module using the require keyword at the top of the file. Assign the reference to a global variable named http. Use let to declare the variable. Import the mysql module using the require keyword at the top of the file. Assign the reference to a global variable named mysql. Use let to declare the variable. Import the events module using the require keyword at the top of the file. Assign the reference to a global variable named events. Use let to declare the variable. 4.2. 4.3. 4.4. Declare variables O O sqlquery, to store query text output, to store output text res, to store a reference to the response object 5. Setup event code 5.1. 5.2. 6.2. 6. Create a Node.js Server 6.1. Invoke the createServer method using your http object. It requires a callback method as an argument. Use method name processServer Request (you will create the method shortly). Store the reference in a new global variable named httpServer. Start the server by invoking its listen method. Configure the server to listen on port 8080. Declare a new object named eventEmitter. Instantiate event Emitter by calling the EventEmitter constructor from within the events object. Assign an event handler to an event by invoking the on method of the event Emitter object. Pass it two arguments: 1) the name of the event, processing Finished, 2) reference to the event handler function, processing FinishedHandler (you will write this method shortly). 7. Implement the method to process HTTP requests. Function Name: processServerRequest Parameters: two: request and response Return value: none Purpose: This method will process HTTP requests. 7.2. The following parts are the body of the method. 7.1. Store the response object received as a parameter in the global variable, res. This will allow you to access the response object in other methods! 7.3. Create the response header by invoking the writeHead method of the response object. Send an OK status code and Content-Type of text/html as arguments. Ensure that you are using the JSON name-value structure (there is no array, so there will be no square brackets). Add the following head tag by invoking the write method of the response object. This will configure a blank favorite icon for the webpage and stop repeated requests for the favicon file. If there was no error, Execute the query by invoking the query method of the con object. Pass the sqlquery text as an argument. In addition, the query method expects a callback function as an argument. Pass a reference to the method processResult as the second argument. (You will write the method shortly). Terminate the connection by calling the end method of the con object. 9. Implement the method to process the results of the query. Function Name: processResult Parameters: two: err and result Return value: none Purpose: This method will process the result of the sql query. It will go through the resultset and invoke a method which can process each record of the resultset. It will also fire or emit an event announcing that the processing of the result has finished. The following parts are the body of the method. 9.1. Using an if statement test if there was an error (using the err variable). If there was an error log it to the console and throw the error again, i.e. "throw err;" Iterate through the result object by calling its for Each method. The forEach 9.2. method requires a callback function as an argument. Pass it the printRecord method reference as an argument. The callback method should know how to process/handle one record. You will write the printRecord method shortly. 9.3. Fire the processing Finished event. Call the emit method of the event Emitter object. Pass it the name of the event you want to fire or "emit" as a string. 10. Implement the method to process one record of the resultset. Function Name: printRecord Parameters: one: record Return value: none Purpose: This method will process one record of the sql resultset. For each record, it will construct a paragraph element which contains the first and last names of the customer. The following parts are the body of the method. 10.1. Using string concatenation, append to the existing output variable. Append a new paragraph tag which contains the first_name and last_name attributes of the record. 11. Implement the method, which serves as the event handler for processingFinished event. Function Name: processing FinishedHandler Parameters: none Return value: none Purpose: This method will handle the event processingFinished. Essentially, once processing is finished, it can write to the response object. The following parts are the body of the method. 11.1. Create a response by invoking the write method of the response object. Within the write method, pass the output variable as an argument. 11.2. End the response by invoking the end method of the global res object. There is no need to write any html as arguments! 12. Test your Program 12.1. Open a command prompt or terminal window. 12.1.1 On MacOS, you can easily open a terminal window which is already within the folder. 12.1.2 On Windows, change directory to work in the exercise folder. You can use the cd command and paste the full folder path. 12.2. Type node followed by the name of the js file to run the file. 12.3. Open Chrome and navigate to the local host server using port 8080. If your program works, it should connect to the Node.js script and execute the full script. The Node.js program should then send an HTML response back. You should then see the first and last names of customers within individual paragraph elements. Ideally, you shouldn't see erroneous output since the database and the response code should execute in proper sequence due to the event firing/handling mechanism. Getting an undefined? You may see "undefined" as an output. If you don't initialize the output variable, it is undefined at the start! Getting multiple copies of the same output? The Node.js response object uses a buffer to write to the response stream. If you refresh, Node.js flushes the buffer. That is why if you keep refreshing, output will keep getting added to the page. 7.4. Assign a SQL select statement to your global sqlquery variable. Within the query, select the first 5 records from the customer table and retrieve only the first and last name columns. 7.5. Call the initializeDB () method. You will write it shortly! 8. Implement the method to connect to the database and perform other database tasks Function Name: initializeDB Parameters: none Return value: none Purpose: This function will use the MySQL module to connect to the database, run a query and terminate the connection. 8.1. Declare a variable named connectionString and assign to a JavaScript object. It should have the following name/value pairs. Ensure that you are using the JSON name- value structure (there is no array, so there will be no square brackets). 8.2. 8.3. Name host database user password Value cis425.wpcclasses.com sakila cis425Fall2021 User cis425Fall2021 Log the connection string to the console. Create a connection by invoking the createConnection method of the mysql object. Pass the connectionString to the method as an argument.createConnection will return a reference to the new connection object. Store it in a new variable named con. 8.4. Log that you are going to connect to the database. 8.5. Start the connection by invoking the connect method of the con object. Pass an inline function declaration as an argument. The function should accept one variable, err, as an argument. The following statements are the body of the inline function. The function is anonymous, i.e. it doesn't have a name. 8.6. Use an if statement to test if there was an error (using the err variable). If there was an error, log the error and throw the err object, i.e. "throw err;". Sample Output HTML file, after connecting to localhost localhost:8080 X + localhost:8080 MARY SMITH PATRICIA JOHNSON LINDA WILLIAMS BARBARA JONES ELIZABETH BROWN 2 Overview In this assignment, you will implement a custom event, which will be fired or "emitted" as well as handled by you. The database will be queried and the results output to a webpage. However, the webpage can only be created after the query results are processed. This will be implemented using an event. The processing of the results will be associated with an event. After the event happens, a method will handle it and print the results to a webpage. 1. Create a new Project folder 1.1. Rename the folder for the assignment. Name the folder in the structure asuriteE#, replacing # with the assignment number. 1.2. Create a blank file and name it events.js 2. Install the mysql package using NPM 2.1. Open a command prompt or terminal window and change the directory to your project folder. 2.2. Use npm install mysql to install the mysql package. 3. Setup the files 3.1. Add your name, assignment #, class, and class time as a comment at the top of the both JavaScript file e.g., John Smith, E13, CIS 235,9 am Work on the JavaScript file 4. Create Global Variables 4.1. Import the http module using the require keyword at the top of the file. Assign the reference to a global variable named http. Use let to declare the variable. Import the mysql module using the require keyword at the top of the file. Assign the reference to a global variable named mysql. Use let to declare the variable. Import the events module using the require keyword at the top of the file. Assign the reference to a global variable named events. Use let to declare the variable. 4.2. 4.3. 4.4. Declare variables O O sqlquery, to store query text output, to store output text res, to store a reference to the response object 5. Setup event code
Expert Answer:
Related Book For
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill
Posted Date:
Students also viewed these programming questions
-
can someone solve this Modern workstations typically have memory systems that incorporate two or three levels of caching. Explain why they are designed like this. [4 marks] In order to investigate...
-
answer the question clearly You are building a flight-control system for which a convincing safety case must be made. Would you assign the tasks of safety requirements engineering, test case...
-
What is the difference between a market system and a market? How Can you have a market without a market system? Why or why not? How about the other way around? Can you have a market system without a...
-
On January 1, 2016. Metco. Inc.. reported 822.100 Problem 8.26 shares of $5 par value common stock as being issued and outstanding. On March 15, 2016. Metco. Inc.. purchased for its treasury 7,200...
-
Donna, age 42 and a single taxpayer, has a salary of $112,000 and interest income of $20,000. What is the maximum amount Donna can contribute to a Roth IRA for 2022? a. $4,800 b. $5,400 c. $5,800 d....
-
Healthy Bite Mart reported the following comparative income statement for the years ended November 30, 2010 and 2009. During 2010, Healthy Bite Mart discovered that the 2009 ending inventory, as...
-
Carl, a salesman for Smith, comes to Bensons home and sells him a complete set of gourmet cooking utensils that are worth approximately $300. Benson, an eighty-year-old man living alone in a one-room...
-
A company must lease a machine for NOK 500,000 over four years. The leasing fee will be 11,500 pr. month. In addition, a payment fee of NOK 25 is required each month. Both the leasing fee and the fee...
-
Given two arrays each of length n, arr1, and arr2, in one operation, any two elements of an array can be swapped. This can occur any number of times. Find the maximum possible sum of i*(arr2[1]-...
-
After gathering data for a report on cubicle height and work productivity, you decide to use a survey to get measurable qualitative and quantitative feedback. What are the advantages of using a...
-
Handy Home sells windows ( 6 0 % of sales ) and doors ( 4 0 % of sales ) . The selling price of each window is $ 4 0 0 and of each door is $ 9 0 0 . The variable cost of each window is $ 2 2 5 and of...
-
Kohl Company provides warranties for many of its products. The January 1 , 2 0 2 2 , balance of the Estimated Warranty Liability account was $ 2 5 , 1 0 0 . Based on an analysis of warranty claims...
-
Consider the given partial LINDO Code: MAX 50 BR+ 20 IC + 30 COLA + 80 PC s.t. 40 BR+ 20 IC + 15 COLA + 50 PC
-
1 : Refer to a case study - Australia Post in Appendix A List at least five change requirements. Part 2: Discuss with your classmates who play the role of managers/specialists to identify major...
-
The gallbladder has a capacity of between 1.2 and 1.7 fluidounces. What is the capacity in milliliters of a gallbladder thatcan hold 1.42 fluid ounces? (There are 32 fl oz/qt.)
-
= $1500 and We consider a 7-year straight term bond issued currently. It has face value F redemption value C = $1800. The annual coupon rate is 7% payable quarterly. The current annual effective...
-
Show, if u(x, y) and v(x, y) are harmonic functions, that u + v must be a harmonic function but that uv need not be a harmonic function. Is e"e" a harmonic function?
-
On February 2, 2012, Alexandra purchases a personal computer for her home. The computer cost $3,000. Alexandra uses the computer 80 percent of the time in her accounting business, 10 percent of the...
-
In 2012, Margaret and John Murphy are married taxpayers who file a joint tax return with AGl of $25,000. During the year they incurred the following expenses: Hospitalization insurance...
-
Rebecca and Walter Bunge have been married for 5 years. They live at 883 Scrub Brush Street, Apt. 52B, Las Vegas, NV 89125. Rebecca is a homemaker and Walt is a high school teacher. Rebecca's Social...
-
The major reason that the difference and ratio estimation methods would be expected to produce audit efficiency compared to mean estimation is that the a. Number of members of the populations of...
-
Probability proportional to size sampling (PPS) is normally used when it is thought that the population contains a a. Few understatements. b. Large number of understatements. c. Few overstatements....
-
Vale has decided to use PPS sampling in the audit of a client's accounts receivable balances. Vale plans to use the following PPS sampling table: What sample size should Vale use? a. 120 b. 108 c. 60...
Study smarter with the SolutionInn App