Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const url = require("url");
- const fs = require("fs");
- const qs = require("querystring");
- const path = require("path");
- //const formidable = require('formidable');
- const cats = require("../data/cats.json");
- const breeds = require("../data/breeds.json");
- module.exports = (req, res) => {
- const pathname = url.parse(req.url).pathname;
- if (pathname === "/cats/add-cat" && req.method === "GET") {
- let filePath = path.normalize(path.join(__dirname, "../views/addCat.html"));
- fs.readFile(filePath, (err, data) => {
- if (err) {
- console.log(err);
- res.writeHead(404, {
- "Content-Type": "text/plain",
- });
- res.write("404 not found :(");
- res.end();
- return;
- }
- res.writeHead(200, {
- "Content-Type": "text/html",
- });
- res.write(data);
- res.end();
- });
- } else if (pathname === "/cats/add-breed" && req.method === "GET") {
- let filePath = path.normalize(
- path.join(__dirname, "../views/addBreed.html")
- );
- fs.readFile(filePath, (err, data) => {
- if (err) {
- console.log(err);
- res.writeHead(404, {
- "Content-Type": "text/plain",
- });
- res.write("404 not found :(");
- res.end();
- return;
- }
- res.writeHead(200, {
- "Content-Type": "text/html",
- });
- res.write(data);
- res.end();
- });
- } else if (pathname === "/cats/add-breed" && req.method === "POST") {
- let formData = "";
- req.on("data", (data) => {
- formData += data;
- });
- req.on("end", () => {
- let body = qs.parse(formData);
- fs.readFile("../data/breeds.json", (err, data) => {
- if (err) {
- throw err;
- }
- let breeds = JSON.parse(data);
- breeds.push(body.breed);
- let json = JSON.stringify(breeds);
- fs.writeFile("../data/breeds.json", json, "utf-8", () =>
- console.log("The breed was uploaded successfully!")
- );
- });
- res.writeHead(302, { location: "/" });
- res.end();
- });
- } else {
- true;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment