2024-04-15 23:24:48 +02:00
|
|
|
import fs from 'fs';
|
|
|
|
import path from 'path';
|
|
|
|
import { promisify } from 'util';
|
|
|
|
|
|
|
|
import { resizeImages } from '../ssg_hooks/resizeImages.js'
|
|
|
|
|
2024-04-16 14:19:14 +02:00
|
|
|
export async function cacheImages(imageSizes) {
|
2024-04-15 23:24:48 +02:00
|
|
|
const sourceFolder = './.output/public/api/assets';
|
|
|
|
const destinationFolder = './public/api/assets';
|
|
|
|
|
|
|
|
if (!fs.existsSync(destinationFolder)) fs.mkdirSync(destinationFolder, { recursive: true });
|
|
|
|
|
|
|
|
const readdir = promisify(fs.readdir);
|
|
|
|
const stat = promisify(fs.stat);
|
|
|
|
const copyFile = promisify(fs.copyFile);
|
|
|
|
|
|
|
|
async function directoryExists(directoryPath) {
|
|
|
|
try {
|
|
|
|
const stats = await fs.promises.stat(directoryPath);
|
|
|
|
return stats.isDirectory();
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code === 'ENOENT') {
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function copyFilesIfNotExist(sourceFolder, destinationFolder) {
|
|
|
|
try {
|
|
|
|
const exists = await directoryExists(sourceFolder);
|
|
|
|
if (!exists) {
|
|
|
|
console.log(`Source folder '${sourceFolder}' does not exist.`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const files = await readdir(sourceFolder);
|
|
|
|
for (const file of files) {
|
|
|
|
const sourceFilePath = path.join(sourceFolder, file);
|
|
|
|
const destinationFilePath = path.join(destinationFolder, file);
|
|
|
|
const sourceFileStat = await stat(sourceFilePath);
|
|
|
|
|
|
|
|
if (sourceFileStat.isFile()) {
|
|
|
|
try {
|
|
|
|
await stat(destinationFilePath);
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code === 'ENOENT') {
|
|
|
|
await copyFile(sourceFilePath, destinationFilePath);
|
|
|
|
console.log(`Copied '${file}' to '${destinationFolder}'.`);
|
|
|
|
} else {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
console.log('Files copied successfully.');
|
|
|
|
|
|
|
|
console.log('Start images resizing.');
|
|
|
|
|
|
|
|
await resizeImages(imageSizes);
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error:', error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
copyFilesIfNotExist(sourceFolder, destinationFolder);
|
|
|
|
}
|