Skip to content

Commit

Permalink
perf: download and save mkcert in stream (#63527)
Browse files Browse the repository at this point in the history
Previously, Next.js would buffer the `mkcert` binary in memory and write
it to disk all at once. The pull request changes this to pipe the
download stream to the disk. This improves memory consumption by
avoiding having to load the entire `mkcert` binary into memory.

---------

Co-authored-by: JJ Kasper <[email protected]>
  • Loading branch information
SukkaW and ijjk authored Mar 26, 2024
1 parent 8d8ffa8 commit a70e55e
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions packages/next/src/lib/mkcert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import path from 'path'
import { getCacheDirectory } from './helpers/get-cache-directory'
import * as Log from '../build/output/log'
import { execSync } from 'child_process'
const { WritableStream } = require('node:stream/web') as {
WritableStream: typeof global.WritableStream
}

const MKCERT_VERSION = 'v1.4.4'

Expand Down Expand Up @@ -53,10 +56,37 @@ async function downloadBinary() {

Log.info(`Download response was successful, writing to disk`)

const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const binaryWriteStream = fs.createWriteStream(binaryPath)

await response.body.pipeTo(
new WritableStream({
write(chunk) {
return new Promise((resolve, reject) => {
binaryWriteStream.write(chunk, (error) => {
if (error) {
reject(error)
return
}

resolve()
})
})
},
close() {
return new Promise((resolve, reject) => {
binaryWriteStream.close((error) => {
if (error) {
reject(error)
return
}

resolve()
})
})
},
})
)

await fs.promises.writeFile(binaryPath, buffer)
await fs.promises.chmod(binaryPath, 0o755)

return binaryPath
Expand Down

0 comments on commit a70e55e

Please sign in to comment.