Canonical: https://nitride.xyz/docs/typescript

# Node.js receiver

Receive the stream with Node's built-in dgram module. No packages to install. It runs on Node 20 or later and on Bun.

## Run it
Save the script as `receiver.mjs` and start it with your UDP port as the first argument. A second argument is optional: an address to accept exclusively. Add it only after delivery is active: support gives you the source address then, so while you verify there is nothing to filter on. Datagrams made of printable characters, which is what the token is, appear as `text from` lines.

```ts file="receiver.mjs"
// receiver.mjs: node receiver.mjs 9000 [source-ip]
import dgram from "node:dgram";

const PORT = Number(process.argv[2] ?? 9000);
const SOURCE = process.argv[3]; // optional: only accept this sender
const COMMON_HEADER = 83;

const sock = dgram.createSocket({ type: "udp4", recvBufferSize: 8 * 1024 * 1024 });

let packets = 0;
let last = { slot: 0n, index: 0, fec: 0 };

sock.on("message", (msg, rinfo) => {
  if (SOURCE && rinfo.address !== SOURCE) return;
  if (msg.length > 0 && msg.every((b) => b === 9 || b === 10 || b === 13 || (b >= 32 && b < 127))) {
    console.log(`text from ${rinfo.address}: ${msg.toString("ascii").trim()}`);
    return;
  }
  if (msg.length < COMMON_HEADER) return;
  packets++;
  last = {
    slot: msg.readBigUInt64LE(65),
    index: msg.readUInt32LE(73),
    fec: msg.readUInt32LE(79),
  };
});

setInterval(() => {
  console.log(`packets=${packets} slot=${last.slot} index=${last.index} fec=${last.fec}`);
  packets = 0;
}, 1000);

sock.bind(PORT, "0.0.0.0", () => console.log(`listening on udp://0.0.0.0:${PORT}`));
```

```sh file="terminal"
node receiver.mjs 9000
```

## What it prints
Once a second, the number of datagrams received and the header of the latest one. The offsets are the shred’s common header: slot at byte 65, index at 73 and FEC set index at 79, all little-endian. The full layout is on the [Rust receiver](https://nitride.xyz/docs/rust#the-header) page.

## Limits of a JavaScript receiver
The event loop handles one datagram per callback, as the [Python receiver](https://nitride.xyz/docs/receiver/python) does one per call; the [Go receiver](https://nitride.xyz/docs/receiver/go) is a compiled alternative with the same output. That is fine for confirming delivery and for light processing. Under bursts, a busy event loop lets the socket buffer fill and the kernel drops what doesn’t fit.

> [!TIP]
> For production, receive in a compiled language and pass parsed results to Node, or at least keep the `message` handler free of any work beyond copying the packet.

## Next
Raise the kernel’s buffer limit so `recvBufferSize` takes effect: see [receive-side requirements](https://nitride.xyz/docs/udp#tuning). The [quickstart](https://nitride.xyz/docs) covers the steps before this one, and the [command-line checks](https://nitride.xyz/docs/cli) help when packets go missing.
