@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
75 lines (74 loc) • 2.93 kB
TypeScript
import { TcpConnectOptions, TcpSocketStream, UdpBindOptions, UdpConnectOptions, UdpSocket, UdpSocketStream, UnixConnectOptions, UnixSocketStream } from "./net/types.ts";
import { getInternetIp } from "./net/util.ts";
export { getInternetIp };
export type * from "./net/types.ts";
/**
* Returns the IP address of the current machine.
*
* NOTE: This function may return the IP address of the local network or the
* public IP address, depending on the environment and network configuration.
* If the public IP address is intended, use {@link getInternetIp} instead.
*/
export declare function getMyIp(): Promise<string>;
/**
* Returns a random port number that is available for listening.
*
* NOTE: This function is not available in the browser and worker runtimes such
* as Cloudflare Workers.
*
* @param prefer The preferred port number to return if it is available,
* otherwise a random port is returned.
*
* @param hostname The hostname to bind the port to. Default is "0.0.0.0", only
* used when `prefer` is set and not `0`.
*/
export declare function randomPort(prefer?: number | undefined, hostname?: string | undefined): Promise<number>;
/**
* This function provides a unified interface to connect to a TCP server or UDP
* peer in Node.js, Deno, Bun and Cloudflare Workers, based on modern Web APIs.
*
* NOTE: This function depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
*
* @example
* ```ts
* // TCP
* import bytes from "@ayonli/jsext/bytes";
* import { readAsText } from "@ayonli/jsext/reader";
* import { connect } from "@ayonli/jsext/net";
*
* const socket = await connect({ hostname: "example.com", port: 80 });
* const writer = socket.writable.getWriter();
*
* await writer.write(bytes("GET / HTTP/1.1\r\n"));
* await writer.write(bytes("Accept: plain/html\r\n"));
* await writer.write(bytes("Host: example.com\r\n"));
* await writer.write(bytes("\r\n"));
* await writer.close();
*
* const message = await readAsText(socket.readable);
* console.log(message);
* ```
*/
export declare function connect(options: TcpConnectOptions): Promise<TcpSocketStream>;
export declare function connect(options: UnixConnectOptions): Promise<UnixSocketStream>;
export declare function connect(options: UdpConnectOptions): Promise<UdpSocketStream>;
/**
* This function provides a unified interface to bind a UDP socket in Node.js,
* Deno and Bun, based on modern Web APIs.
*
* NOTE: This function depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
*
* @example
* ```ts
* import { udpSocket } from "@ayonli/jsext/net";
*
* const socket = await udpSocket({ port: 8080 });
*
* for await (const [data, addr] of socket) {
* console.log(`Received ${data.byteLength} bytes from ${addr.hostname}:${addr.port}`);
* }
* ```
*/
export declare function udpSocket(localAddress?: UdpBindOptions): Promise<UdpSocket>;