HTTP Server with Node.js

  1. Essential Roles of a Virtualization Hypervisor:

    • (b) Scheduling CPU time slices 4 each virtual machine.
    • (c) Exposing custom virtualized hardware.
    • (d) Allocating system resources across guest operating systems.

    Hypervisors R responsible 4 managing virtual machines by allocating resources & scheduling CPU time. Direct disk access is typically managed through the hypervisor but is not considered a direct role of the hypervisor as it involves more direct interaction with the guest OS.

  2. Relationship of Docker Containers 2 Docker Images:

    • (c) Docker containers execute Docker image contents.

    Docker images serve as the blueprint from which containers R created & run, including all dependencies & environment necessary 4 the application.

  3. Meaning of “Stateless” in HTTP:

    • (b) Each client request is independent of previous requests.

    HTTP is stateless, meaning that each request from a client 2 server is treated as an entirely new request without any memory of past interactions.

  4. Comparison Returning False:

    • (b) ‘5’ === 5.

    In JavaScript, ‘===’ is the strict equality operator that checks 4 both value & type equality. Since ‘5’ is a string & 5 is a number, this comparison returns false.

  5. Output of Node.Js
    Snippet:

    • Let’s analyze & run the snippet 2 determine the correct answer.
  6. Result of Running Code with Non-existent File:

    • (b) The process crashes with an uncaught exception.

    Node.Js’s asynchronous fs.ReadFile method’s error handling must occur within the callback function. Using throw inside an asynchronous callback does not lead 2 the catch block catching it outside the asynchronous operation.

  7. Output of Node.Js Snippet (String Prototype Modification):

    • (a) AlphaOmega BetaOmega AlphaOmega.

    Modifying the prototype method after the objects have been created affects all instances of the object, as the method resolution occurs @ runtime when the method is called.

  8. Output of Node.Js Snippet (Calculator Function):

    • We need 2 analyze the code 2 determine the correct output, considering the default parameters & rest parameters syntax.
  9. Output of Node.Js Snippet (Async Functions):

    • (b) Apple Statement1 Banana Statement2.

    The order of execution is determined by the timing of the promises & the placement of console logs relative 2 asynchronous operations.

  10. Effect of Multiple Callback Calls:

    • (b) All calls will execute.

    In Node.Js, if a callback function is called multiple times within a single execution phase, each call will be executed in the order they were called.


Free-Response Questions

    1. Behavior of Node.Js Snippet (Large Number Arithmetic):

      • We need 2 compute the values of A52 & A53 & understand the behavior of large number arithmetic in JavaScript 2 answer this question.
    2. Outputs of Node.Js Code Snippets:

      • We’ll analyze each snippet 2 determine what, if anything, they will output 2 the console.
    3. Encrypted msg Service Implementation:

      • This task requires completing the given starter code with specific functionalities 4 handling users, messages, & encryption. Given the scope, the implementation involves creating an express application, defining API routes, & implementing the required logic 4 each route using Node.Js & the provided classes & methods.

hw2p1 code

Const http = require(‘http’);


2
const fs = require('fs');


3
const url = require('url');


4

5
const factorial = (n) => {

6
  let res = BigInt(1);


7
  for (let i = 2; i <= n; i++) {

8
    res *= BigInt(i);


9
  }

10
  return res;


11
};


12

13
const numAna = (s) => {

14
  if (!S || s.Trim() === '' || !/^[a-zA-Z]+$/.Test(s)) return "0";


15
  s = s.ToLowerCase();


16
  const charDict = {};


17

18
  for (const char of s) {

19
    if (!CharDict[char]) {

20
      charDict[char] = 1;


21
    } else {

22
      charDict[char]++;


23
    }

24
  }

25

26
  let res = factorial(s.Length);


27
  for (const count of Object.Values(charDict)) {

28
    res /= factorial(count);


29
  }

30

31
  return res.ToString();


32
};


33

34
let reqCount = 0;


35
let errCount = 0;


36

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

38
  const parsedUrl = url.Parse(req.Url, true);


39
  const path = parsedUrl.Pathname;


40
  const query = parsedUrl.Query;


41

42
  reqCount++;



44
  if (req.Method === 'GET') {

45
    switch (path) {

46
      case '/ping':

47
        res.WriteHead(204);

48
        res.End();

49
        break;

50
      case '/anagram':

51
        const p = query.P;

52
        if (!P || p.Trim() === '' || !/^[a-zA-Z]+$/.Test(p)) {

53
          errCount++;

54
          res.WriteHead(400, { 'Content-Type': 'application/json' });

55
          res.End(JSON.Stringify({ error: "Parameter 'p' is required and must be alphabetical." }));

56
        } else {

57
          const totalAnagrams = numAna(p);

58
          res.WriteHead(200, { 'Content-Type': 'application/json' });

59
          res.End(JSON.Stringify({ p: p, total: totalAnagrams }));

60
        }

61
        break;

62

63
      case '/secret':

64
        fs.Exists('/tmp/secret.Key', (exists) => {

65
          if (exists) {

66
            fs.ReadFile('/tmp/secret.Key', (err, data) => {

67
              if (err) {

68
                console.Error(err);

69
                res.WriteHead(500);

70
                res.End();

71
                return;

72
              }

73
              res.WriteHead(200, { 'Content-Type': 'text/plain' });

74
              res.End(data);

75
            });

76
          } else {

77
            errCount++;

78
            res.WriteHead(404);

79
            res.End();

80
          }

81
        });

82
        break;

83

84
      case '/status':

85
        res.WriteHead(200, { 'Content-Type': 'application/json' });

86
        const currentTime = new Date().ToISOString().Replace(/\.\d{3}/, '');

87
        res.End(JSON.Stringify({ time: currentTime, req: reqCount, err: errCount }));

88
        break;

89

90
      default:

91
        errCount++;

92
        res.WriteHead(404);

93
        res.End();

94
    }

95
  } else {

96
    errCount++;

97
    res.WriteHead(405);

98
    res.End();

99
  }

100
});

101

102
server.Listen(8088, () => {

103
  console.Log('Server running on port 8088');

104
});