Update server.js
Browse files
server.js
CHANGED
|
@@ -1,10 +1,19 @@
|
|
| 1 |
const express = require("express");
|
| 2 |
const { chromium } = require("playwright");
|
| 3 |
const bodyParser = require("body-parser");
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
const app = express();
|
| 6 |
app.use(bodyParser.text({ type: "text/html" }));
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
app.post("/v1/start", async (req, res) => {
|
| 9 |
const html = req.body;
|
| 10 |
if (!html) return res.status(400).send("HTML required");
|
|
@@ -12,11 +21,31 @@ app.post("/v1/start", async (req, res) => {
|
|
| 12 |
const browser = await chromium.launch({ args: ["--no-sandbox"] });
|
| 13 |
const page = await browser.newPage();
|
| 14 |
await page.setContent(html);
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
await browser.close();
|
| 18 |
-
|
| 19 |
-
res.
|
| 20 |
});
|
| 21 |
|
| 22 |
-
app.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
const express = require("express");
|
| 2 |
const { chromium } = require("playwright");
|
| 3 |
const bodyParser = require("body-parser");
|
| 4 |
+
const fs = require("fs");
|
| 5 |
+
const path = require("path");
|
| 6 |
+
const os = require("os");
|
| 7 |
|
| 8 |
const app = express();
|
| 9 |
app.use(bodyParser.text({ type: "text/html" }));
|
| 10 |
|
| 11 |
+
const tmpDir = os.tmpdir();
|
| 12 |
+
|
| 13 |
+
function randomFilename() {
|
| 14 |
+
return Math.random().toString(36).slice(2, 6) + ".png";
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
app.post("/v1/start", async (req, res) => {
|
| 18 |
const html = req.body;
|
| 19 |
if (!html) return res.status(400).send("HTML required");
|
|
|
|
| 21 |
const browser = await chromium.launch({ args: ["--no-sandbox"] });
|
| 22 |
const page = await browser.newPage();
|
| 23 |
await page.setContent(html);
|
| 24 |
+
|
| 25 |
+
const filename = randomFilename();
|
| 26 |
+
const filepath = path.join(tmpDir, filename);
|
| 27 |
+
await page.screenshot({ path: filepath });
|
| 28 |
|
| 29 |
await browser.close();
|
| 30 |
+
|
| 31 |
+
res.json({ url: `${req.protocol}://${req.get("host")}/t/${filename}` });
|
| 32 |
});
|
| 33 |
|
| 34 |
+
app.use("/t", (req, res, next) => {
|
| 35 |
+
fs.readdir(tmpDir, (err, files) => {
|
| 36 |
+
if (err) return next();
|
| 37 |
+
const now = Date.now();
|
| 38 |
+
files.forEach((file) => {
|
| 39 |
+
const filePath = path.join(tmpDir, file);
|
| 40 |
+
fs.stat(filePath, (err, stats) => {
|
| 41 |
+
if (err) return;
|
| 42 |
+
if (now - stats.ctimeMs > 5 * 60 * 1000) {
|
| 43 |
+
fs.unlink(filePath, () => {});
|
| 44 |
+
}
|
| 45 |
+
});
|
| 46 |
+
});
|
| 47 |
+
});
|
| 48 |
+
next();
|
| 49 |
+
}, express.static(tmpDir));
|
| 50 |
+
|
| 51 |
+
app.listen(process.env.PORT || 7860);
|