0.1.0 • Published yesterday
@digta/network
Licence
MIT
Version
0.1.0
Deps
1
Size
16 kB
Vulns
0
Weekly
0
@digta/network
Network toolkit for Node: a TCP / WebSocket client with autoreconnect, plus a tiny HTTP API client with retries. Same package, one import.
npm install @digta/network
Connection — TCP / WebSocket + autoreconnect
One API for both transports. Pick it with the URL scheme: tcp://, ws://, or wss://.
import { createConnection } from "@digta/network";
// or: const { createConnection } = require("@digta/network");
const conn = createConnection({
url: "tcp://192.168.1.10:502", // or "ws://host:8080/path"
reconnect: true, // on by default
backoff: { min: 500, max: 30000, factor: 2 },
});
conn.on("connect", () => console.log("connected"));
conn.on("message", (data) => console.log("in:", data));
conn.on("reconnecting", (attempt, delay) => console.log(`retry #${attempt} in ${delay}ms`));
conn.on("close", () => console.log("closed"));
conn.on("error", (err) => console.error(err));
conn.connect();
conn.send("hello");
// conn.close(); // intentional — stops reconnecting
Autoreconnect uses exponential backoff with jitter and resets on success. Call close() to stop for good.
Heartbeat & latency (optional)
Set heartbeat (ms) to ping and measure round-trip time:
const conn = createConnection({ url: "ws://host:8080", heartbeat: 5000 });
conn.on("latency", (ms) => console.log(`${ms}ms`));
conn.on("timeout", () => console.log("no pong — dropping + reconnecting"));
- WebSocket: works out of the box (native ping/pong frames).
- Raw TCP: has no ping frame. Provide your protocol's
pingbytes and anisPong(data)matcher, or rely on OS keepalive (always on) for dead-link detection.
Events
connect · message(data) · close · error(err) · reconnecting(attempt, delay) · reconnect_failed(attempts) · latency(ms) · timeout
TCP is a raw byte stream — it has no message framing.
messagefires per chunk; handle your own boundaries. WebSocket messages are framed for you.
API — HTTP client with retries
import { createApi } from "@digta/network";
const api = createApi({
baseURL: "https://api.example.com",
headers: { authorization: "Bearer …" },
timeout: 10000,
retries: 3, // retries network errors, timeouts, 429, and 5xx (exp backoff)
});
const { data, status } = await api.get("/users", { query: { page: 2 } });
await api.post("/users", { name: "digta" }); // JSON body auto-serialized
await api.get("/thing", { retries: 0, timeout: 2000 }); // per-request overrides
- JSON bodies are serialized and
Content-Typeset automatically; JSON responses are parsed. 4xx/5xxreject with an error carrying.statusand.response.- Follows redirects (up to 5 hops).
- Zero HTTP dependency — built on Node's
http/https, works on Node 14+.
For one-off absolute-URL calls, use the ready api:
import { api } from "@digta/network";
const res = await api.get("https://example.com/health");
License
MIT