mahee-auffret/ssg_hooks/cacheImages.js

69 lines
2.3 KiB
JavaScript

import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { resizeImages } from '../ssg_hooks/resizeImages.js'
export async function cacheImages(imageSizes) {
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);
}