Assingment: Nodejs http module and fs module

View on github

Question

In this assignment, you will build a server using 
NodeJs http module & fs module. Your
server should listen on port 3000.

Requirements
Your file server should meet the following requirements:

1.It should use the http module to create an HTTP server.
2.It should listen on port 3000.
3.It should log a message to the console when it starts listening on port 3000.
4.If you request this url “/” then the response is “This is Home Page”.
5.If you request this url “/about” then the response is “This is About Page”.
6.If you request this url “/contact” then the response is “This is Contact Page”.
7.If you request this url “/file-write” then fs.writeFile() method will create a file
“demo.txt” and write the text “hello world” in this file.
8.And of course you need to end the server response using res.end()

Instructions:
Follow these instructions to complete the assignment:
Create a new file named server.js.
Write the code for your file server in server.js
                                

Answer

                                    
    const http = require('http');
    const fs = require('fs');

    const server = http.createServer((req, res) => {
        // Log a message when the server starts listening
        console.log('Server is listening on port 3000');

        // Set content type for the response
        res.setHeader('Content-Type', 'text/plain');

        // Handle different URL paths
        if (req.url === '/') {
            res.end('This is Home Page');
        } else if (req.url === '/about') {
            res.end('This is About Page');
        } else if (req.url === '/contact') {
            res.end('This is Contact Page');
        } else if (req.url === '/file-write') {
            // Use fs.writeFile to create a file and write content
            fs.writeFile('demo.txt', 'hello world', (err) => {
                if (err) {
                    res.statusCode = 500;
                    res.end('Internal Server Error');
                } else {
                    res.end('File demo.txt created and content written');
                }
            });
        } else {
            res.statusCode = 404;
            res.end('Page not found');
        }
    });

    // Listen on port 3000
    server.listen(3000);