-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (56 loc) · 1.47 KB
/
server.js
File metadata and controls
62 lines (56 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const http = require("http");
const fs = require("fs");
const path = require("path");
const queryString = require("querystring");
const GET = "GET";
const POST = "POST";
const PORT = process.env.port||80
const headers = {
"Access-Control-Allow-Origin": "*",
};
const arraydb = [
{ type: "autoplay", result: 30 },
{ type: "single", result: 30 },
{ type: "versus", result: 30 },
];
const loadResult = async (pathUrl) => {
const data = fs.readFileSync(pathUrl, "utf-8");
return data;
};
const writeResult = async (pathUrl, obj) => {
const data = fs.writeFileSync(pathUrl, JSON.stringify(obj));
return data;
};
http
.createServer(async (req, res) => {
const pathUrl = path.join("db", `${req.url}.json`);
let readReq;
if (req.method === GET) {
const pathUrl = path.join("db", `${req.url}.json`);
console.log(pathUrl);
readReq = await loadResult(pathUrl);
console.log("ответ отправляется");
res.writeHead(200, headers);
res.end(readReq);
}
if (req.method === POST) {
console.log("куку");
let body = "";
let result;
req.on("data", (chunk) => (body += chunk.toString()));
req.on("end", async () => {
await writeResult(pathUrl,JSON.parse(body));
res.writeHead(200, headers);
res.end(result);
});
}
if (req.method === "OPTIONS") {
res.header({
"Access-Control-Allow-Methods": "GET,POST,OPTIONS,DELETE,PUT",
});
res.send();
}
})
.listen(PORT, () => {
console.log("сервер запущен");
});