Skip to content

Commit

Permalink
fix(node/http): don't throw on .address() before .listen() (#24432)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
marvinhagemeister committed Jul 4, 2024
1 parent f632b4a commit 96b527b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
3 changes: 2 additions & 1 deletion ext/node/polyfills/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1657,7 1657,7 @@ export class ServerImpl extends EventEmitter {
#httpConnections: Set<Deno.HttpConn> = new Set();
#listener?: Deno.Listener;

#addr: Deno.NetAddr;
#addr: Deno.NetAddr | null = null;
#hasClosed = false;
#server: Deno.HttpServer;
#unref = false;
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions tests/unit_node/http_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit 96b527b

Please sign in to comment.