Simple Node.js server breakdown

·

3 min read

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

const server = http.createServer((req, res) => {

const readWrite = (file,contentType) => {
  fs.readFile(file, function(err, data) {
    res.writeHead(200, {'Content-Type': contentType});
    res.write(data);
    res.end();
  });
}

  const page = url.parse(req.url).pathname;
  const params = querystring.parse(url.parse(req.url).query);
  console.log(page);

  switch (page) {
    case '/':
      readWrite('index.html','text/html')
      break;
    case '/otherpage':
      readWrite('otherpage.html','text/html')
      break;
    case '/otherotherpage':
      readWrite('otherotherpage.html','text/html')
      break;
    case '/api':


        // let personName = 'unknown'
        // let personStatus = 'unknown'
        // let personOccupation = 'unknown'
        let flipResult = "type 'flip' in the input box"
        if (params['student']== 'flip') {
          flipResult = Math.random() <= 0.5 ? 'heads' : 'tails'
        }  

          //   personName = 'leon'
          //   personStatus = 'Baller'
          //   personOccupation = 'Boss man'
          // }
          res.writeHead(200, {'Content-Type': 'application/json'});
          const objToJson = {
            name: flipResult,
            // status: personStatus,
            // currentOccupation: personOccupation,
          }
          res.end(JSON.stringify(objToJson));
      break;
    case '/css/style.css':
      fs.readFile('css/style.css', function(err, data) {
        res.write(data);
        res.end();
      }); 
      break;
    case '/js/main.js':
      readWrite('js/main.js', 'text/javascript')  
      break;
      default:
        figlet('404!!', function(err, data) {
          if (err) {
              console.log('Something went wrong...');
              console.dir(err);
              return;
          }
          res.write(data);
          res.end();
        });
        break;
  }

});

server.listen(8000);
  1. First, it loads some tools it needs. These are Node.js tools that help it do its job. These tools let it understand HTTP requests (http), read files (fs), understand web addresses (url), understand certain information sent with those addresses (querystring), and create cool text art (figlet).

  2. It then sets up a helper named readWrite, which is like a special clerk who can find a file in the back office and bring it to the front desk. This is used when someone wants to see a specific page on our website.

  3. It then sets up a helper named readWrite, which is like a special clerk who can find a file in the back office and bring it to the front desk. This is used when someone wants to see a specific page on our website.

  4. Our doorman then gets ready to start receiving visitors. It looks at the visitor's request (where they want to go) and uses this information to decide what to do next.

  5.  const server = http.createServer((req, res) => {
       const page = url.parse(req.url).pathname;
       const params = querystring.parse(url.parse(req.url).query);
       console.log(page);
       ...
     });
    

    Here, http.createServer creates the "doorman", which starts working whenever a request comes in.

    const page = url.parse(req.url).pathname; is where the doorman looks at the visitor's request. It checks which URL (which page or "room" in the building) the visitor wants to go to.

    const params = querystring.parse(url.parse(req.url).query); is where the doorman checks if the visitor is making a special request (like asking for a coin flip in the '/api' section of our building).

    Then console.log(page); is where the doorman notes down where each visitor is trying to go. This is mainly for the doorman (our server) to keep track of visitor activity; it doesn't affect the visitor's experience.

  6. If someone asks for '/api' with a specific request (like asking for a coin flip), our doorman flips a virtual coin and tells them whether it's 'heads' or 'tails'.

  7. If someone asks for the design or behavior of the website ('/css/style.css', '/js/main.js'), it fetches that too.

  8. And if a visitor asks for a place that doesn't exist, it shows them a ASCII art of '404!!' sign, which is like saying, "Oops, we couldn't find the page you're looking for."

  9. Finally, it waits at the door (port 8000) for visitors to start arriving.