source: Klonkt/src/services/ImageWebpService.js@ db81e56

main
Last change on this file since db81e56 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 1.6 KB
Line 
1/**
2 * Convert a freshly uploaded image to WebP (smaller, modern format).
3 *
4 * Uses the system `cwebp` (libwebp). Present → convert + delete the original,
5 * return the new .webp filename. Not present or error → return the original
6 * filename (graceful fallback, nothing breaks).
7 *
8 * GIF stays GIF (cwebp cannot produce animated WebP from a GIF); already-WebP
9 * files are skipped.
10 */
11import { execFileSync } from 'child_process';
12import fs from 'fs';
13import path from 'path';
14
15const QUALITY = '82';
16
17/**
18 * @param {{path:string, filename:string, destination?:string}} file multer file
19 * @returns {string} the final filename (basename) — .webp or the original
20 */
21export function toWebp(file) {
22 if (!file || !file.path || !file.filename) return file && file.filename;
23 const ext = path.extname(file.filename).toLowerCase();
24 if (ext === '.webp' || ext === '.gif') return file.filename;
25 const dir = file.destination || path.dirname(file.path);
26 const outName = path.basename(file.filename, ext) + '.webp';
27 const outPath = path.join(dir, outName);
28 try {
29 execFileSync('cwebp', ['-quiet', '-q', QUALITY, file.path, '-o', outPath], { stdio: 'ignore' });
30 if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) throw new Error('empty output');
31 try { fs.unlinkSync(file.path); } catch { /* original gone, not critical */ }
32 return outName;
33 } catch (e) {
34 console.warn('[webp] conversion skipped (cwebp not available/error):', e.message);
35 try { if (fs.existsSync(outPath)) fs.unlinkSync(outPath); } catch {} // clean up partial output
36 return file.filename; // keep original
37 }
38}
39
40export default { toWebp };
Note: See TracBrowser for help on using the repository browser.