From 4658fae3591f5806cce85e71c6db6decde0206c6 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Thu, 10 Feb 2022 18:39:12 -0600 Subject: [PATCH] Use updated recursive rm fs method for image-optimizer --- packages/next/server/image-optimizer.ts | 31 ++++++++++++++++++------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/next/server/image-optimizer.ts b/packages/next/server/image-optimizer.ts index 2d5c73b6dc417..56feff6010b32 100644 --- a/packages/next/server/image-optimizer.ts +++ b/packages/next/server/image-optimizer.ts @@ -240,14 +240,18 @@ export class ImageOptimizerCache { Math.max(revalidate, this.nextConfig.images.minimumCacheTTL) * 1000 + Date.now() - await writeToCacheDir( - join(this.cacheDir, cacheKey), - value.extension, - revalidate, - expireAt, - value.buffer, - value.etag - ) + try { + await writeToCacheDir( + join(this.cacheDir, cacheKey), + value.extension, + revalidate, + expireAt, + value.buffer, + value.etag + ) + } catch (err) { + console.error(`Failed to write image to cache ${cacheKey}`, err) + } } } export class ImageError extends Error { @@ -543,7 +547,16 @@ async function writeToCacheDir( etag: string ) { const filename = join(dir, `${maxAge}.${expireAt}.${etag}.${extension}`) - await promises.rmdir(dir, { recursive: true }) + + // Added in: v14.14.0 https://nodejs.org/api/fs.html#fspromisesrmpath-options + // attempt cleaning up existing stale cache + if ((promises as any).rm) { + await (promises as any) + .rm(dir, { force: true, recursive: true }) + .catch(() => {}) + } else { + await promises.rmdir(dir, { recursive: true }).catch(() => {}) + } await promises.mkdir(dir, { recursive: true }) await promises.writeFile(filename, buffer) }