/ lab8 / app.js
app.js
 1  import http from "http";
 2  import fs from "fs";
 3  import path from "path";
 4  
 5  const inMemoryPasswords = [];
 6  
 7  const server = http.createServer((req, res) => {
 8      console.log(`${req.method} request for: ${req.url}`);
 9  
10      if (req.method === "POST" && req.url === "/submit") {
11          let body = "";
12  
13          req.on("data", (chunk) => {
14              body += chunk.toString();
15          });
16  
17          req.on("end", () => {
18              try {
19                  const data = JSON.parse(body);
20                  if (data.password) {
21                      inMemoryPasswords.push(data.password);
22                      console.log("Password saved in memory:", data.password);
23                      console.log("All saved passwords:", inMemoryPasswords);
24                  }
25              } catch (e) {
26                  console.log("Received POST data:", body);
27              }
28  
29              res.writeHead(200, { "Content-Type": "text/html" });
30              res.end("<h1>POST received! Check the console.</h1>");
31          });
32      } else if (req.url === "/" || req.url === "/index.html") {
33          const filePath = path.join(process.cwd(), "password_generator", "index.html");
34          fs.readFile(filePath, (err, data) => {
35              if (err) {
36                  res.writeHead(500, { "Content-Type": "text/plain" });
37                  res.end("Internal Server Error");
38                  return;
39              }
40              res.writeHead(200, { "Content-Type": "text/html" });
41              res.end(data);
42          });
43      } else if (req.url === "/script.js") {
44          const filePath = path.join(process.cwd(), "password_generator", "script.js");
45  
46          fs.readFile(filePath, (err, data) => {
47              if (err) {
48                  res.writeHead(404, { "Content-Type": "text/plain" });
49                  res.end("Not Found");
50                  return;
51              }
52              res.writeHead(200, { "Content-Type": "application/javascript" });
53              res.end(data);
54          });
55      } else {
56          res.writeHead(404, { "Content-Type": "text/html" });
57          res.write("<h1>404 Not Found</h1>");
58          res.end();
59      }
60  });
61  
62  const PORT = process.env.PORT || 3000;
63  server.listen(PORT, () => {
64      console.log(`Server running at http://localhost:${PORT}/`);
65  });