cache des images resize

This commit is contained in:
Valentin
2024-04-16 14:19:14 +02:00
parent 5ae12fdc14
commit 4bd30ff772
10 changed files with 55 additions and 25 deletions

View File

@@ -4,7 +4,7 @@ import { promisify } from 'util';
import { resizeImages } from '../ssg_hooks/resizeImages.js'
export async function cacheImages() {
export async function cacheImages(imageSizes) {
const sourceFolder = './.output/public/api/assets';
const destinationFolder = './public/api/assets';
@@ -57,11 +57,6 @@ export async function cacheImages() {
console.log('Files copied successfully.');
console.log('Start images resizing.');
const imageSizes = [
{ small: 750 },
{ large: 1920 },
];
await resizeImages(imageSizes);

View File

@@ -1,35 +1,49 @@
import fs from 'fs';
import path from 'path';
import sharp from 'sharp';
import { promisify } from 'util';
export async function resizeImages(sizes) {
const stat = promisify(fs.stat);
const copyFile = promisify(fs.copyFile);
const sourceFolder = './public/api/assets';
const outputFolder = './.output/public';
const outputFolder = './.output/public/imgs';
const sizeCacheFolder = './public/imgs';
for (const size of sizes) {
const key = Object.keys(size)[0];
const sizeFolder = `${outputFolder}/${key}`;
if (!fs.existsSync(sizeFolder)) {
fs.mkdirSync(sizeFolder, { recursive: true });
}
if (!fs.existsSync(sizeFolder)) fs.mkdirSync(sizeFolder, { recursive: true });
const cacheSizeFolder = `${sizeCacheFolder}/${key}`;
if (!fs.existsSync(cacheSizeFolder)) fs.mkdirSync(cacheSizeFolder, { recursive: true });
}
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];
const sizeFolder = `${outputFolder}/${key}`;
const width = parseInt(size[key]);
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;
}
}
await image.clone().resize({ width }).toFile(`${sizeFolder}/${file}`);
}
}
// fs.rmSync('./.output/public/api/assets', { recursive: true, force: true });
fs.rmSync('./.output/public/api/assets', { recursive: true, force: true });
console.log('Images resized and saved successfully.');
console.log('Images resized and cached successfully.');
}