mahee-auffret/ssg_hooks/resizeImages.js

49 lines
1.7 KiB
JavaScript

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/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 });
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 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;
}
}
}
}
fs.rmSync('./.output/public/api/assets', { recursive: true, force: true });
console.log('Images resized and cached successfully.');
}