fast72 commited on
Commit
58d4f83
·
verified ·
1 Parent(s): b273a4f

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +8 -36
server.js CHANGED
@@ -1,56 +1,28 @@
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
  try {
19
  const html = req.body;
20
- if (!html) return res.status(400).json({ error: "HTML required" });
21
 
22
- const browser = await chromium.launch({ args: ["--no-sandbox", "--disable-setuid-sandbox"] });
23
  const page = await browser.newPage();
24
  await page.setContent(html, { waitUntil: "load" });
25
 
26
- const filename = randomFilename();
27
- const filepath = path.join(tmpDir, filename);
28
- await page.screenshot({ path: filepath });
29
 
30
  await browser.close();
31
 
32
- res.json({ url: `${req.protocol}://${req.get("host")}/t/${filename}` });
33
- } catch (error) {
34
- console.error("Error:", error);
35
- res.status(500).json({ error: "Internal Server Error" });
36
  }
37
  });
38
 
39
- app.use("/t", (req, res, next) => {
40
- fs.readdir(tmpDir, (err, files) => {
41
- if (err) return next();
42
- const now = Date.now();
43
- files.forEach((file) => {
44
- const filePath = path.join(tmpDir, file);
45
- fs.stat(filePath, (err, stats) => {
46
- if (err) return;
47
- if (now - stats.ctimeMs > 5 * 60 * 1000) {
48
- fs.unlink(filePath, () => {});
49
- }
50
- });
51
- });
52
- });
53
- next();
54
- }, express.static(tmpDir));
55
-
56
- app.listen(process.env.PORT || 7860, () => console.log("Server running..."));
 
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
  try {
10
  const html = req.body;
11
+ if (!html) return res.sendStatus(400);
12
 
13
+ const browser = await chromium.launch({ args: ["--no-sandbox"] });
14
  const page = await browser.newPage();
15
  await page.setContent(html, { waitUntil: "load" });
16
 
17
+ const buffer = await page.screenshot({ type: "png" });
 
 
18
 
19
  await browser.close();
20
 
21
+ res.setHeader("Content-Type", "image/png");
22
+ res.send(buffer);
23
+ } catch {
24
+ res.sendStatus(500);
25
  }
26
  });
27
 
28
+ app.listen(7860);