| 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 | */
|
|---|
| 11 | import { execFileSync } from 'child_process';
|
|---|
| 12 | import fs from 'fs';
|
|---|
| 13 | import path from 'path';
|
|---|
| 14 |
|
|---|
| 15 | const 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 | */
|
|---|
| 21 | export 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 |
|
|---|
| 40 | export default { toWebp };
|
|---|