Cross-runtime TCP and Unix domain socket operations.
Node, Deno, and Bun use runtime-selected native socket adapters exposed as
Web Streams. Browser bundles can import this package, but net.open()
rejects because browsers do not expose raw TCP or Unix sockets.
import net from "@rcompat/net";
import type {
NetOptions, Socket, TCPOptions, UnixOptions,
} from "@rcompat/net";net.open#
Opens a TCP or Unix domain socket.
Pass { host, port } for TCP or { path } for a Unix domain socket.
Connection and address errors from the selected runtime are propagated.
Parameters
options— TCP address or Unix socket path.
Returns: A socket backed by native Web Streams.
Throws: In browsers, always rejects because raw sockets are unavailable.
net.open(options: NetOptions): Promise<Socket>;Example
const socket = await net.open({ host: "127.0.0.1", port: 9000 });
await socket.write("hello");
await socket.close();Types#
Socket#
A connected TCP or Unix socket backed by Web Streams.
Instances are created by net.open(); the class is exported only as a type.
declare class Socket {}Instance properties#
socket.readable#
Stream of bytes received from the peer.
Reading with text() or async iteration locks this stream while
that operation is active.
socket.readable: ReadableStream<Uint8Array>;socket.writable#
Stream used to send bytes to the peer.
The socket holds this stream's writer; use write(), end(), or
close() rather than acquiring another writer.
socket.writable: WritableStream<Uint8Array>;Instance methods#
socket.write()#
Writes text or bytes to the peer.
Strings are encoded as UTF-8; byte arrays are written unchanged.
Parameters
data— Text or bytes to write.
socket.write(data: string | Uint8Array): Promise<void>socket.end()#
Closes the writable side while leaving the readable side open.
Use this half-close when the peer responds after receiving EOF.
socket.end(): Promise<void>socket.close()#
Closes the writable side and cancels the readable side.
socket.close(): Promise<void>socket.text()#
Drains received bytes and decodes them as streaming UTF-8 text.
Returns: The decoded response after the readable stream ends.
socket.text(): Promise<string>Protocol members#
socket[Symbol.asyncIterator]()#
Iterates byte chunks received from the peer.
socket[Symbol.asyncIterator](): AsyncIterator<Uint8Array>NetOptions#
TCP or Unix domain socket connection options.
type NetOptions = TCPOptions | UnixOptions;TCPOptions#
TCP connection address.
interface TCPOptions {
// Hostname or IP address to connect to.
host: string;
// TCP port to connect to.
port: number;
}UnixOptions#
Unix domain socket address.
interface UnixOptions {
// Filesystem path of the Unix domain socket.
path: string;
}