fix: error "port busy" printed twice

Massimo Melina committed Dec 6, 2024 at 20:04 UTC b42baef2381202876a9e8f23d574bb3f8b6908d8
1 file changed +9 -6
src/listen.ts
+9 -6
@@ -187,8 +187,10 @@ export function startServer(srv: typeof httpSrv, { port, host }: StartServer) {
187 return new Promise<number>(async resolve => {
188 if (!srv) return resolve(0)
189 try {
190 - if (port === PORT_DISABLED || !host && !await testIpV4()) // !host means ipV4+6, and if v4 port alone is busy we won't be notified of the failure, so we'll first test it on its own
190 + if (port === PORT_DISABLED)
191 return resolve(0)
192 + if (!host && !await testIpV4()) // !host means ipV4+6, and if v4 port alone is busy we won't be notified of the failure, so we'll first test it on its own
193 + throw srv.error
194 // from a few tests, this seems enough to support the expect-100 http/1.1 mechanism, at least with curl -T, not used by chrome|firefox anyway
195 srv.on('checkContinue', (req, res) => srv.emit('request', req, res))
196 port = await listen(host)
@@ -198,18 +200,18 @@ export function startServer(srv: typeof httpSrv, { port, host }: StartServer) {
200 }
201 catch(e) {
202 srv.error = String(e)
201 - console.error(srv.name, "couldn't listen on port", port, srv.error)
203 + console.error(srv.name, `couldn't listen on port ${port}:`, srv.error)
204 resolve(0)
205 }
206 })
207
208 async function testIpV4() {
207 - const res = await listen('0.0.0.0')
208 - await new Promise(res => srv?.close(res))
209 + const res = await listen('0.0.0.0', true)
210 + await new Promise(res => srv?.close(res)) // close, if any, and wait
211 return res > 0
212 }
213
212 - function listen(host?: string) {
214 + function listen(host?: string, silence=false) {
215 return new Promise<number>(async (resolve, reject) => {
216 srv?.on('error', onError).listen({ port, host }, () => {
217 const ad = srv.address()
@@ -235,7 +237,8 @@ export function startServer(srv: typeof httpSrv, { port, host }: StartServer) {
237 res?.map(x => prefix("Service", x.name === 'svchost.exe' && x.cmd.split(x.name)[1]?.trim()) || x.name).join(' + '), () => '')
238 srv.error = `port ${port} busy: ${await srv.busy || "unknown process"}`
239 }
238 - console.error(srv.name, srv.error)
240 + if (!silence)
241 + console.error(srv.name, srv.error)
242 resolve(0)
243 }
244 })