mirror of
https://github.com/denoland/std.git
synced 2024-11-21 20:50:22 +00:00
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:
parent
67bbf14d89
commit
1dc2369865
18
net/get_available_port.ts
Normal file
18
net/get_available_port.ts
Normal 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;
|
||||
}
|
20
net/get_available_port_test.ts
Normal file
20
net/get_available_port_test.ts
Normal 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
9
net/mod.ts
Normal 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";
|
Loading…
Reference in New Issue
Block a user