настроить модули express-session и coockie-parser
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);