-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (45 loc) · 1.39 KB
/
index.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
56
57
import { isAbsolute, join, sep } from "path";
import { existsSync, readFileSync } from "fs";
import express from "express";
import sharp from "sharp";
const port = 19092;
const allowedOutFormats = new Set([
"jpeg",
"png",
"webp",
"gif",
"avif",
"tiff",
]);
const app = express();
app.get("/", async (req, res) => {
try {
if (!req.query.filepath || !req.query.format)
return res.status(400).send("Bad Request");
const filePath = req.query.filepath,
format = req.query.format;
if (
!isAbsolute(filePath) ||
!existsSync(filePath) ||
!allowedOutFormats.has(format)
) {
return res.status(400).send("Bad Request");
}
const fileParts = filePath.split(sep),
fileDir = fileParts.slice(0, fileParts.length - 1).join(sep),
fileName = fileParts[fileParts.length - 1],
fileNoExt = fileName.split(".")[0];
if (existsSync(join(fileDir, `${fileNoExt}.${format}`)))
return res.status(200).send("OK");
const file = readFileSync(filePath);
await sharp(file)
.toFormat(format)
.toFile(join(fileDir, `${fileNoExt}.${format}`));
return res.status(200).send("OK");
} catch (err) {
console.error(err);
return res.status(500).send("Internal Server Error");
}
});
app.get("/health", (req, res) => res.status(200).send("OK"));
app.listen(port, () => console.log(`Server listening on port ${port}`));