Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Expand Your HTTP Server to Serve Different Static Files Based on the URL

Steps:

  1. Step 1: Create a file fileServer.js.

  2. 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');
    });
  3. Step 3: Create sample HTML files:

    • index.html:

      html코드 복사<h1>Welcome to the Home Page</h1>
    • about.html:

      html코드 복사<h1>About Us</h1>
  4. Step 4: Run the server:

    bash코드 복사node fileServer.js
  5. Step 5: Test the server:

    • Visit http://localhost:3000/ to view the Home Page.

    • Visit http://localhost:3000/about.html to view the About Page.


Research and Write a Short Note on Streams:

  • Key Points:

    1. Streams process data in chunks, improving memory usage for large files.

    2. Types of streams: Readable, Writable, Duplex, and Transform.

    3. Example use cases: File I/O, video streaming, and real-time data processing.

Expected Outcomes

  1. Students become proficient in using the fs, http, and stream modules for practical tasks.

  2. Hands-on activities prepare students for server-side programming challenges.

  3. Homework reinforces their understanding of file serving and stream performance benefits.

Last updated