-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (46 loc) · 1.43 KB
/
server.js
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
const http = require("http");
const fs = require("fs");
const crypto = require("crypto");
const path = require("path");
const PORT = process.env.PORT || 3000;
const FOLDER = process.env.FOLDER || "./db";
if (!fs.existsSync(FOLDER)) fs.mkdirSync(FOLDER);
function hash(data) {
const hash = crypto.createHash("sha1");
hash.update(data);
return hash.digest("hex").slice(0, 10);
}
const server = http.createServer((req, res) => {
const end = (code, body) => {
res.writeHead(code, { "Access-Control-Allow-Origin": "*" });
res.end(body);
};
if (req.method === "OPTIONS") end(200);
else if (req.method === "POST") {
let requestBody = "";
req.on("data", (chunk) => {
requestBody += chunk;
});
req.on("end", () => {
const pathName = path.join(FOLDER, `${hash(requestBody)}.txt`);
console.log(`POST ${pathName}`);
fs.writeFile(pathName, requestBody, (err) => {
if (err) return end(500);
end(200);
});
});
} else if (req.method === "GET") {
const hash = req.url.slice(1);
// Prevents directory traversal
if (!hash.match(/^[0-9a-f]+$/)) return end(404);
const pathName = path.join(FOLDER, `${hash}.txt`);
console.log(`GET ${pathName}`);
fs.readFile(pathName, "utf8", (err, data) => {
if (err) return end(404);
end(200, data);
});
} else end(405);
});
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});