feat(net): getAvailablePort() (#3890)

Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
Harry Solovay 2023-12-03 23:50:40 -05:00 committed by GitHub
parent 67bbf14d89
commit 1dc2369865
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 0 deletions

18
net/get_available_port.ts Normal file
View File

@ -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;
}

View File

@ -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://localhost:${port}`);
const text = await resp.text();
assertEquals(text, "hello");
server.shutdown();
},
}, () => new Response("hello"));
await server.finished;
});

9
net/mod.ts Normal file
View File

@ -0,0 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
/**
* Network utilities.
*
* @module
*/
export * from "./get_available_port.ts";