47 lines
1.0 KiB
JavaScript
47 lines
1.0 KiB
JavaScript
import fs from "node:fs/promises";
|
|
import { posix as path } from "node:path";
|
|
import { fsCachePath } from "../../utils/runtimeChecks.js";
|
|
|
|
const copied = [];
|
|
let assetsDirExists;
|
|
|
|
export async function saveAndCopyAsset(
|
|
hash,
|
|
image,
|
|
buffer,
|
|
outDir,
|
|
assetsDir,
|
|
assetPath,
|
|
isSsrBuild
|
|
) {
|
|
const src = fsCachePath + hash;
|
|
|
|
const dest = path.join(outDir, isSsrBuild ? "/client" : "", assetPath);
|
|
|
|
assetsDir = path.join(outDir, isSsrBuild ? "/client" : "/", assetsDir);
|
|
|
|
if (copied.includes(assetPath)) return;
|
|
|
|
if (!assetsDirExists) {
|
|
await fs.mkdir(assetsDir, {
|
|
recursive: true,
|
|
});
|
|
|
|
assetsDirExists = true;
|
|
}
|
|
|
|
await fs.copyFile(src, dest).catch(async (error) => {
|
|
if (error.code === "ENOENT") {
|
|
const imageBuffer = buffer || (await image.toBuffer());
|
|
|
|
await Promise.all(
|
|
[src, dest].map(async (dir) => {
|
|
await fs.writeFile(dir, imageBuffer);
|
|
})
|
|
);
|
|
} else throw error;
|
|
});
|
|
|
|
copied.push(assetPath);
|
|
}
|