-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (54 loc) · 1.51 KB
/
index.js
File metadata and controls
61 lines (54 loc) · 1.51 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
require("dotenv").config();
const fs = require("fs");
const path = require("path");
const cors = require("cors");
const JSONdb = require("simple-json-db");
const nanoid = require("nanoid").nanoid;
const express = require("express");
const app = express();
const PORT = process.env.PORT || 8080;
const MAX_FILE_SIZE = process.env.MAX_FILE_SIZE || 1024 * 1024 * 50; // 50MB
const db = new JSONdb(path.join(__dirname, "database.json"));
app.use(cors());
app.use(express.static("public"));
app.get("/:id", (req, res) => {
let id = req.params.id;
let file = db.get(id);
if (file) {
return res.download(path.join(__dirname, "files", id), file.name);
} else {
return res.sendStatus(404);
}
});
app.post("/:name", (req, res) => {
let id = nanoid();
let contentLength = req.header("Content-Length");
if (contentLength > MAX_FILE_SIZE) {
req.destroy();
res.sendStatus(413);
} else {
let file = fs.createWriteStream(path.join(__dirname, "files", id));
let size = 0;
req
.on("data", (data) => {
size += data.length;
if (size > MAX_FILE_SIZE) {
req.destroy();
file.close();
fs.unlinkSync(path.join(__dirname, "files", id));
} else {
file.write(data);
}
})
.on("end", () => {
db.set(id, {
name: req.params.name,
createdAt: Date.now(),
});
res.send(id);
});
}
});
app.listen(PORT, () => {
console.log(`send-it server listening on http://localhost:${PORT}`);
});