mahee-auffret/ssg_hooks/resizeImages.js

49 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-04-15 23:24:48 +02:00
import fs from 'fs';
2024-04-16 14:19:14 +02:00
import path from 'path';
2024-04-15 23:24:48 +02:00
import sharp from 'sharp';
2024-04-16 14:19:14 +02:00
import { promisify } from 'util';
2024-04-15 23:24:48 +02:00
export async function resizeImages(sizes) {
2024-04-16 14:19:14 +02:00
const stat = promisify(fs.stat);
const copyFile = promisify(fs.copyFile);
2024-04-15 23:24:48 +02:00
const sourceFolder = './public/api/assets';
2024-04-16 14:19:14 +02:00
const outputFolder = './.output/public/imgs';
const sizeCacheFolder = './public/imgs';
2024-04-15 23:24:48 +02:00
for (const size of sizes) {
const key = Object.keys(size)[0];
const sizeFolder = `${outputFolder}/${key}`;
2024-04-16 14:19:14 +02:00
if (!fs.existsSync(sizeFolder)) fs.mkdirSync(sizeFolder, { recursive: true });
const cacheSizeFolder = `${sizeCacheFolder}/${key}`;
if (!fs.existsSync(cacheSizeFolder)) fs.mkdirSync(cacheSizeFolder, { recursive: true });
2024-04-15 23:24:48 +02:00
}
const files = fs.readdirSync(sourceFolder);
for (const file of files) {
const filePath = `${sourceFolder}/${file}`;
const image = sharp(filePath);
for (const size of sizes) {
const key = Object.keys(size)[0];
2024-04-16 14:19:14 +02:00
const destinationFile = path.join(sizeCacheFolder, key, file);
try {
const destinationFileStat = await stat(destinationFile);
} catch (error) {
if (error.code === 'ENOENT') {
const width = parseInt(size[key]);
await image.clone().resize({ width }).toFile(destinationFile);
await copyFile(destinationFile, path.join(outputFolder, key, file));
} else {
throw error;
}
}
2024-04-15 23:24:48 +02:00
}
}
2024-04-16 14:19:14 +02:00
fs.rmSync('./.output/public/api/assets', { recursive: true, force: true });
2024-04-15 23:24:48 +02:00
2024-04-16 14:19:14 +02:00
console.log('Images resized and cached successfully.');
2024-04-15 23:24:48 +02:00
}