Homework & Coding Practice
Homework/Practice Coding Assignment (20-min)
Expand Your HTTP Server to Serve Different Static Files Based on the URL
Steps:
Step 1: Create a file
fileServer.js.Step 2: Add the following code:
javascript코드 복사const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { const filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url); fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('404 Not Found'); } res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(data); }); }); server.listen(3000, () => { console.log('File server running at http://localhost:3000'); });Step 3: Create sample HTML files:
index.html:html코드 복사<h1>Welcome to the Home Page</h1>about.html:html코드 복사<h1>About Us</h1>
Step 4: Run the server:
bash코드 복사node fileServer.jsStep 5: Test the server:
Visit
http://localhost:3000/to view the Home Page.Visit
http://localhost:3000/about.htmlto view the About Page.
Research and Write a Short Note on Streams:
Key Points:
Streams process data in chunks, improving memory usage for large files.
Types of streams: Readable, Writable, Duplex, and Transform.
Example use cases: File I/O, video streaming, and real-time data processing.
Expected Outcomes
Students become proficient in using the
fs,http, andstreammodules for practical tasks.Hands-on activities prepare students for server-side programming challenges.
Homework reinforces their understanding of file serving and stream performance benefits.
Last updated