@sntran/socket
v0.3.0
Published
Cross runtime Socket API
Downloads
4
Readme
@sntran/socket
Cross runtime implementation of the proposed Socket API.
On Node, a custom implementation on top of node:net
and node:tls
is used.
Deno uses the same implementation with buit-in polyfills. On Cloudflare Workers,
cloudflare:sockets
is used.
Usage
See examples for more detailed usage.
import { connect } from "@sntran/socket";
export default {
async fetch(request) {
const gopherAddr = { hostname: "gopher.floodgap.com", port: 70 };
const url = new URL(req.url);
try {
const socket = connect(gopherAddr);
const writer = socket.writable.getWriter();
const encoder = new TextEncoder();
const encoded = encoder.encode(url.pathname + "\r\n");
await writer.write(encoded);
return new Response(socket.readable, {
headers: { "Content-Type": "text/plain" },
});
} catch (error) {
return new Response("Socket connection failed: " + error, {
status: 500,
});
}
},
};