Homework & Coding Practice
Homework/Practice Coding Assignment (10-min)
Part 1: Write a Summary (5 minutes)
Write a one-page summary addressing the following:
What is the Node.js event loop, and why is it important?
How does Node.js manage multiple operations efficiently in a single-threaded environment?
Include one example of how the event loop improves application performance.
Part 2: Practice Coding
Step-by-Step Procedure with Sample Code:
Install Node.js:
Download from nodejs.org and install on your system.
Verify installation with:
bash코드 복사node -v npm -v
Explore Non-Blocking I/O with
setTimeout:Create a file
eventLoopExample.js:javascript코드 복사console.log('Start of the program'); setTimeout(() => { console.log('Executed after 2 seconds'); }, 2000); console.log('End of the program');Steps:
Open a terminal.
Navigate to the file location.
Run:
node eventLoopExample.js.
Expected Output:
sql코드 복사Start of the program End of the program Executed after 2 secondsKey Learning Point: Node.js does not block the program while waiting for the timer.
Build a Simple HTTP Server:
Create a file
server.js:javascript코드 복사const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, Node.js!'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });Steps:
Save the file.
Run:
node server.js.Open
http://localhost:3000in a browser.
Expected Output in Browser: "Hello, Node.js!"
Key Learning Point: Demonstrates the simplicity of creating a server using Node.js.
Extend the Server with Asynchronous File Reading:
Update
server.js:javascript코드 복사const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => { fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error reading file'); return; } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); }); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });Create a file
example.txtwith sample content: "Welcome to Node.js file handling."Steps:
Run:
node server.js.Visit
http://localhost:3000.
Expected Output in Browser: "Welcome to Node.js file handling."
Key Learning Point: Understand how Node.js handles asynchronous file operations.
Analyze Outputs and Observations:
Document the order of log statements and browser outputs.
Relate findings to the Node.js event loop phases.
Expected Outcomes:
Students understand the practical application of Node.js features.
Hands-on exploration reinforces lecture concepts.
Homework ensures reflection on the event loop and its impact.
Last updated