Skip to content

Commit

Permalink
Use updated recursive rm fs method for image-optimizer (#34210)
Browse files Browse the repository at this point in the history
This ensures we handle `EEXISTS` with `fs.rmdir` for Node.js `v12` and use `fs.rm` when available instead as it is the replacement for `fs.rmdir` with the `recursive` option. 

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Fixes: #33860 (comment)
  • Loading branch information
ijjk committed Feb 11, 2022
1 parent a38e144 commit fa5571a
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions packages/next/server/image-optimizer.ts
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit fa5571a

Please sign in to comment.