victoriaSD

cat shelter

Sep 12th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const url = require("url");
  2. const fs = require("fs");
  3. const qs = require("querystring");
  4. const path = require("path");
  5. //const formidable = require('formidable');
  6. const cats = require("../data/cats.json");
  7. const breeds = require("../data/breeds.json");
  8.  
  9. module.exports = (req, res) => {
  10.   const pathname = url.parse(req.url).pathname;
  11.  
  12.   if (pathname === "/cats/add-cat" && req.method === "GET") {
  13.     let filePath = path.normalize(path.join(__dirname, "../views/addCat.html"));
  14.  
  15.     fs.readFile(filePath, (err, data) => {
  16.       if (err) {
  17.         console.log(err);
  18.         res.writeHead(404, {
  19.           "Content-Type": "text/plain",
  20.         });
  21.  
  22.         res.write("404 not found :(");
  23.         res.end();
  24.         return;
  25.       }
  26.  
  27.       res.writeHead(200, {
  28.         "Content-Type": "text/html",
  29.       });
  30.       res.write(data);
  31.       res.end();
  32.     });
  33.   } else if (pathname === "/cats/add-breed" && req.method === "GET") {
  34.     let filePath = path.normalize(
  35.       path.join(__dirname, "../views/addBreed.html")
  36.     );
  37.     fs.readFile(filePath, (err, data) => {
  38.       if (err) {
  39.         console.log(err);
  40.         res.writeHead(404, {
  41.           "Content-Type": "text/plain",
  42.         });
  43.  
  44.         res.write("404 not found :(");
  45.         res.end();
  46.         return;
  47.       }
  48.  
  49.       res.writeHead(200, {
  50.         "Content-Type": "text/html",
  51.       });
  52.       res.write(data);
  53.       res.end();
  54.     });
  55.   } else if (pathname === "/cats/add-breed" && req.method === "POST") {
  56.     let formData = "";
  57.  
  58.     req.on("data", (data) => {
  59.       formData += data;
  60.     });
  61.  
  62.     req.on("end", () => {
  63.       let body = qs.parse(formData);
  64.  
  65.       fs.readFile("../data/breeds.json", (err, data) => {
  66.         if (err) {
  67.           throw err;
  68.         }
  69.  
  70.         let breeds = JSON.parse(data);
  71.         breeds.push(body.breed);
  72.         let json = JSON.stringify(breeds);
  73.  
  74.         fs.writeFile("../data/breeds.json", json, "utf-8", () =>
  75.           console.log("The breed was uploaded successfully!")
  76.         );
  77.       });
  78.  
  79.       res.writeHead(302, { location: "/" });
  80.       res.end();
  81.     });
  82.   } else {
  83.     true;
  84.   }
  85. };
  86.  
Advertisement
Add Comment
Please, Sign In to add comment