Student Activity

Student Activity (30-min)

Step-by-Step Procedure

  1. Write a Program to Read, Write, and Append Data to a File Using the fs Module (15 min):

    • Step 1: Create a file named fileOperations.js.

    • Step 2: Add the following code:

      javascript코드 복사const fs = require('fs');
      
      // Write to a file
      fs.writeFile('example.txt', 'This is an example file.', (err) => {
        if (err) throw err;
        console.log('File created and written to.');
      
        // Read the file
        fs.readFile('example.txt', 'utf8', (err, data) => {
          if (err) throw err;
          console.log('File content:', data);
      
          // Append to the file
          fs.appendFile('example.txt', '\nAppended text.', (err) => {
            if (err) throw err;
            console.log('Content appended to file.');
          });
        });
      });
    • Step 3: Run the script:

      bash코드 복사node fileOperations.js
    • Expected Output:

      • File is created and written to.

      • Content is read from the file and displayed.

      • Additional content is appended to the file.

  2. Create a Simple HTTP Server Using the http Module (15 min):

    • Step 1: Create a file named httpServer.js.

    • Step 2: Add the following code:

      javascript코드 복사const http = require('http');
      
      const server = http.createServer((req, res) => {
        if (req.url === '/') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the Home Page');
        } else if (req.url === '/about') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('This is the About Page');
        } else {
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found');
        }
      });
      
      server.listen(3000, () => {
        console.log('Server running at http://localhost:3000');
      });
    • Step 3: Run the script:

      bash코드 복사node httpServer.js
    • Step 4: Test the server:

      • Visit http://localhost:3000/ for the Home Page.

      • Visit http://localhost:3000/about for the About Page.

      • Visit http://localhost:3000/unknown to test the 404 response.

Last updated