Skip to content

Commit 602d786

Browse files
authored
fix(dev): avoid event emitter leak caused by server.listen callback (#21451)
1 parent ebda8fd commit 602d786

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

packages/vite/src/node/__tests__/plugins/hooks.spec.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ const createPreviewServerWithPlugin = async (plugin: Plugin) => {
5757
name: 'mock-preview',
5858
configurePreviewServer({ httpServer }) {
5959
// NOTE: make httpServer.listen no-op to avoid starting a server
60-
httpServer.listen = (...args: unknown[]) => {
61-
const listener = args.at(-1) as () => void
62-
listener()
60+
httpServer.listen = () => {
61+
const lastListener = httpServer.listeners('listening').at(-1)!
62+
lastListener.call(httpServer)
6363
return httpServer as any
6464
}
6565
},

packages/vite/src/node/http.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -197,14 +197,20 @@ async function tryBindServer(
197197
> {
198198
return new Promise((resolve) => {
199199
const onError = (e: Error & { code?: string }) => {
200-
httpServer.removeListener('error', onError)
200+
httpServer.off('error', onError)
201+
httpServer.off('listening', onListening)
201202
resolve({ success: false, error: e })
202203
}
203-
httpServer.on('error', onError)
204-
httpServer.listen(port, host, () => {
205-
httpServer.removeListener('error', onError)
204+
const onListening = () => {
205+
httpServer.off('error', onError)
206+
httpServer.off('listening', onListening)
206207
resolve({ success: true })
207-
})
208+
}
209+
210+
httpServer.on('error', onError)
211+
httpServer.on('listening', onListening)
212+
213+
httpServer.listen(port, host)
208214
})
209215
}
210216

0 commit comments

Comments
 (0)