HTTP Server with Node.js
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.
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.
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.
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.
Output of Node.Js
Snippet:- Let’s analyze & run the snippet 2 determine the correct answer.
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.
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.
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.
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.
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
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.
Outputs of Node.Js Code Snippets:
- We’ll analyze each snippet 2 determine what, if anything, they will output 2 the console.
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’);
const fs = require('fs');
const url = require('url');
const factorial = (n) => {
let res = BigInt(1);
for (let i = 2; i <= n; i++) {
res *= BigInt(i);
}
return res;
};
const numAna = (s) => {
if (!S || s.Trim() === '' || !/^[a-zA-Z]+$/.Test(s)) return "0";
s = s.ToLowerCase();
const charDict = {};
17
for (const char of s) {
if (!CharDict[char]) {
charDict[char] = 1;
} else {
charDict[char]++;
}
}
25
let res = factorial(s.Length);
for (const count of Object.Values(charDict)) {
res /= factorial(count);
}
30
return res.ToString();
};
33
let reqCount = 0;
let errCount = 0;
36
const server = http.CreateServer((req, res) => {
const parsedUrl = url.Parse(req.Url, true);
const path = parsedUrl.Pathname;
const query = parsedUrl.Query;
41
reqCount++;
if (req.Method === 'GET') {
switch (path) {
case '/ping':
res.WriteHead(204);
res.End();
break;
case '/anagram':
const p = query.P;
if (!P || p.Trim() === '' || !/^[a-zA-Z]+$/.Test(p)) {
errCount++;
res.WriteHead(400, { 'Content-Type': 'application/json' });
res.End(JSON.Stringify({ error: "Parameter 'p' is required and must be alphabetical." }));
} else {
const totalAnagrams = numAna(p);
res.WriteHead(200, { 'Content-Type': 'application/json' });
res.End(JSON.Stringify({ p: p, total: totalAnagrams }));
}
break;
62
case '/secret':
fs.Exists('/tmp/secret.Key', (exists) => {
if (exists) {
fs.ReadFile('/tmp/secret.Key', (err, data) => {
if (err) {
console.Error(err);
res.WriteHead(500);
res.End();
return;
}
res.WriteHead(200, { 'Content-Type': 'text/plain' });
res.End(data);
});
} else {
errCount++;
res.WriteHead(404);
res.End();
}
});
break;
83
case '/status':
res.WriteHead(200, { 'Content-Type': 'application/json' });
const currentTime = new Date().ToISOString().Replace(/\.\d{3}/, '');
res.End(JSON.Stringify({ time: currentTime, req: reqCount, err: errCount }));
break;
89
default:
errCount++;
res.WriteHead(404);
res.End();
}
} else {
errCount++;
res.WriteHead(405);
res.End();
}
});
101
server.Listen(8088, () => {
console.Log('Server running on port 8088');
});
