E
E
evg_962017-09-18 14:41:58
Node.js
evg_96, 2017-09-18 14:41:58

How to process requests with GET, POST, DELETE methods?

After the video lesson, they gave dz to write request processing.
If the request is with the GET method, then give the file from the ./files folder ( http://site.com/file name )
If POST ( http://site.com/file name ), then check if the file is not in ./ files, then create a file and write the data passed on request to it.
If DELETE, then check if the file is in ./files, then delete it.
I've been trying to write a solution to this problem for an hour now, but something doesn't work out.
Wrote a draft...

const http = require("http");
const fs = require("fs");
const url = require("url");

const handlerGET = require("./handlerGET");
const handlerPOST = require("./handlerPOST");
const handlerDELETE = require("./handlerDELETE");

http.createServer((req, res) => {
  const pathname = decodeURI(url.parse(req.url).pathname);

  switch (req.method) {
    case "GET": {
      handlerGET(pathname, req, res); break;
    }

    case "POST": {
      handlerPOST(pathname, req, res); break;
    }

    case "DELETE": {
      handlerDELETE(pathname, req, res); break;
    }

    default: {
      res.statusCode = 502;

      res.end("Not implemented");
    }
  }
}).listen(3000);

const handlerGET = (pathname, req, res) => {
  if (pathname === "/") {
    require("fs").createReadStream(__dirname + "/index.html").pipe(res);
  } else {
    // Проверить если файл есть в директории ./files, то отдать пользователю
  }
};

module.exports = handlerGET;

const handlerPOST = (pathname, req, res) => {
  // Проверить если файла нет в директории ./files, то создать файл и записать в него тело запроса, иначе отправить 409.
  // Также проверить размер файла, если больше 1мб то вернуть ошибку 413.
};

module.exports = handlerPOST;

const handlerDELETE = (pathname, req, res) => {
  // Удалить файл ./files/pathname, вернуть 200, иначе 404.
};

module.exports = handlerDELETE;

Can you tell me how to process these requests according to the condition of the task? Or tell me some article where similar functionality is described
Seems like a solution
const http = require("http");
const fs = require("fs");
const url = require("url");

const public = __dirname + "/files";

http.createServer((req, res) => {
  const pathname = url.parse(req.url).pathname;

  if (pathname === "/") {
    res.writeHead(200, {
      "Content-Type": "text/html"
    });

    fs.createReadStream(__dirname + "/index.html").pipe(res);
  }

  switch (req.method) {
    case "GET": {
      const file = fs.createReadStream(public + pathname);

      file.on("error", err => {
        if (err.code === "ENOENT") {
          res.statusCode = 404;

          res.end("File not found");
        } else {
          res.statusCode = 500;

          res.end("Server error");
        }
      });

      file.on("open", () => {
        res.writeHead(200, {
          "Content-Type": "text/html" // ???
        });
      });

      res.on("close", () => {
        file.destroy();
      });

      file.pipe(res);

      break;
    }

    case "POST": {
      const file = fs.createWriteStream(public + pathname, {
        flags: "wx"
      });

      const maxSize = 1024 * 1024;

      let size = 0;

      file.on("error", err => {
        if (err.code === "EEXIST") {
          res.statusCode = 409;

          res.end("File already exists");
        } else {
          if (!res.headersSent) {
            res.statusCode = 500;

            res.setHeader("Connection", "close");

            res.write("Internal error");
          }

          fs.unlink(pathname, err => {
            res.end();
          });
        }
      });

      file.on("close", () => {
        res.statusCode = 200;

        res.end("OK");
      });

      req.on("data", chunk => {
        size += chunk.length;

        if (size > maxSize) {
          res.statusCode = 413;

          res.setHeader("Connection", "close");

          res.end("Your data too big for my little server");

          file.destroy();

          file.unlink(err => {
            if (err) {
              throw err;
            }
          });
        }
      });

      req.pipe(file);

      break;
    }

    case "DELETE": {
      fs.unlink(public + pathname, err => {
        if (err) {
          res.statusCode = 500;

          res.end("Server error");
        } else {
          res.statusCode = 200;

          res.end("File was deleted");
        }
      });

      break;
    }

    default: {
      res.statusCode = 502;

      res.end("Not implemented");
    }
  }
}).listen(3000);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2017-09-18
@RidgeA

It's not clear what the problem is.
How to work with FS is here - https://nodejs.org/api/fs.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question