Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (48 loc) · 1.66 KB
/
Copy pathserver.js
File metadata and controls
60 lines (48 loc) · 1.66 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
import express from "express";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { config } from "./src/config.js";
import { launchAndCapture } from "./src/browser.js";
import { encodeGif } from "./src/gif.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.static(join(__dirname, "public")));
// Track active generation so we can only run one at a time
let generating = false;
app.post("/api/generate", async (req, res) => {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: "URL is required." });
}
try {
new URL(url);
} catch {
return res.status(400).json({ error: "Invalid URL." });
}
if (generating) {
return res.status(429).json({ error: "A GIF is already being generated. Please wait." });
}
generating = true;
console.log(`\nGenerating GIF for: ${url}`);
try {
const frames = await launchAndCapture(url, config);
const gifBuffer = await encodeGif(frames, config);
const sizeMB = (gifBuffer.length / 1024 / 1024).toFixed(2);
console.log(`Done — ${sizeMB} MB, ${frames.length} frames`);
res.set({
"Content-Type": "image/gif",
"Content-Disposition": 'attachment; filename="output.gif"',
});
res.send(gifBuffer);
} catch (err) {
console.error("Generation failed:", err);
res.status(500).json({ error: "Failed to generate GIF. Check the URL and try again." });
} finally {
generating = false;
}
});
app.listen(PORT, () => {
console.log(`URL-to-GIF server running at http://localhost:${PORT}`);
});