Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(net): getAvailablePort() #3890

Merged
merged 9 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions net/get_available_port.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

/**
* Returns an available network port.
*
* @example
* ```ts
* import { getAvailablePort } from "https://deno.land/std@$STD_VERSION/net/get_available_port.ts";
*
* const port = getAvailablePort();
* Deno.serve({ port }, () => new Response("Hello, world!"));
* ```
*/
export function getAvailablePort(): number {
const listener = Deno.listen({ port: 0 });
listener.close();
return (listener.addr as Deno.NetAddr).port;
iuioiua marked this conversation as resolved.
Show resolved Hide resolved
}
20 changes: 20 additions & 0 deletions net/get_available_port_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

import { getAvailablePort } from "./get_available_port.ts";
import { assertEquals } from "../assert/mod.ts";

Deno.test("getAvailablePort() gets an available port", async () => {
const port = getAvailablePort();

const server = Deno.serve({
port,
async onListen() {
const resp = await fetch(`http:https://localhost:${port}`);
const text = await resp.text();
assertEquals(text, "hello");
server.shutdown();
},
}, () => new Response("hello"));

await server.finished;
});
9 changes: 9 additions & 0 deletions net/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

/**
* Network utilities.
*
* @module
*/

export * from "./get_available_port.ts";