Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
85 lines (73 loc) · 2.45 KB
/
Copy pathserver.js
File metadata and controls
85 lines (73 loc) · 2.45 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import express from "express";
import bodyParser from "body-parser";
import fs from "fs/promises";
import path from "path";
import sharp from "sharp";
const app = express();
app.use(bodyParser.json({ limit: "50mb" }));
app.post("/optimize", async (req, res) => {
try {
const { filename, formats = [], options = {}, outputDir, wait = false } = req.body;
if (!filename || !formats.length || !outputDir) {
return res.status(400).json({
error: "filename, formats, and outputDir are required"
});
}
// Ensure the output directory exists
await fs.mkdir(outputDir, { recursive: true });
// 🔥 Shared processing logic
const processImage = async () => {
const inputBuffer = await fs.readFile(filename);
const tasks = formats.map(async (format) => {
let pipeline = sharp(inputBuffer);
const ext = format === "mozjpeg" ? "jpg" : format;
const outputFile = path.join(
outputDir,
path.basename(filename).replace(/\..+$/, `.${ext}`)
);
// Apply format-specific options
if (format === "webp") {
pipeline = pipeline.webp({ quality: options.webp?.quality ?? 75 });
} else if (format === "mozjpeg") {
pipeline = pipeline.jpeg({ quality: options.mozjpeg?.quality ?? 75 });
} else if (format === "oxipng") {
pipeline = pipeline.png({ compressionLevel: options.oxipng?.level ?? 1 });
} else if (format === "avif") {
pipeline = pipeline.avif({ quality: options.avif?.quality ?? 50 });
}
await pipeline.toFile(outputFile);
console.log(`Image optimization completed: ${outputFile}`);
return {
format,
file: outputFile
};
});
return Promise.all(tasks);
};
if (wait) {
const results = await processImage();
return res.json({
success: true,
results
});
}
// Respond immediately to avoid blocking the request
res.json({ accepted: true });
// Background image optimization
setImmediate(async () => {
try {
await processImage();
} catch (err) {
console.error("Sharp async processing error:", err);
}
});
} catch (err) {
console.error("Server error:", err);
if (!res.headersSent) {
return res.status(500).json({ error: "Server error" });
}
}
});
app.listen(3000, () => {
console.log("Sharp image-optimizer running on port 3000");
});