From 96b527b8df3c9e7e29c98a6a0d6876089b88bc09 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Thu, 4 Jul 2024 18:28:48 +0200 Subject: fix(node/http): don't throw on .address() before .listen() (#24432) It's perfectly valid to access `server.address()` before calling `.listen()`. Until a server actively listens on a socket Node will return `null` here, but we threw a "Cannot access property 'port' of undefined" instead. This was discovered when inspecting failures in Koa's test suite with Deno. --- ext/node/polyfills/http.ts | 3 ++- tests/unit_node/http_test.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index b1a536113..40155d998 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -1657,7 +1657,7 @@ export class ServerImpl extends EventEmitter { #httpConnections: Set = new Set(); #listener?: Deno.Listener; - #addr: Deno.NetAddr; + #addr: Deno.NetAddr | null = null; #hasClosed = false; #server: Deno.HttpServer; #unref = false; @@ -1843,6 +1843,7 @@ export class ServerImpl extends EventEmitter { } address() { + if (this.#addr === null) return null; return { port: this.#addr.port, address: this.#addr.hostname, diff --git a/tests/unit_node/http_test.ts b/tests/unit_node/http_test.ts index aeb92f129..0935aeac0 100644 --- a/tests/unit_node/http_test.ts +++ b/tests/unit_node/http_test.ts @@ -1251,3 +1251,8 @@ Deno.test("[node/http] http.request() post streaming body works", async () => { clearTimeout(timeout); assertEquals(server.listening, false); }); + +Deno.test("[node/http] Server.address() can be null", () => { + const server = http.createServer((_req, res) => res.end("it works")); + assertEquals(server.address(), null); +}); -- cgit v1.2.3