Editors Choice

3/recent/post-list

HTTP Methods

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

const myServer = http.createServer((req, res) => {
    if (req.url === "/favicon.ico") {
        res.end();
    }
    const d = new Date();
    const myUrl = url.parse(req.url);
    const log = `Recieved a ${req.method}: ${myUrl.path} at ${d.getDate()}/${d.getMonth()}/${d.getFullYear()}\n`;

    fs.appendFile('log.txt',log, (err)=>{
        if(err)
        {
            console.log(`Error Writing Files ${err}`);
        }
        else{
            console.log(log);
        }
    } )
    switch (myUrl.pathname) {
        case '/':
            res.end('This is home page');
            break;
        case '/about':
            res.end('This is about page');
            break;
        case '/contact':
            res.end('This is contact page');
            break;
    }
});

myServer.listen(8080, ()=>{
    console.log("Server running at port 8080");
})

Post a Comment

0 Comments