1.0.0 • Published 5 years ago

udp-to-readable-stream v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

UDP to Readable Stream

CircleCI npm version

Read data from a UDP socket into a readable stream. No dependencies.

If you encounter an issue, fork the repository, write tests demonstrating the issue, and create a pull request.

const udpToReadableStream = require('udp-to-readable-stream');
const crypto = require('crypto');

const chunks = [
  crypto.randomBytes(Math.round(Math.random() * 256)),
  crypto.randomBytes(Math.round(Math.random() * 256)),
  crypto.randomBytes(Math.round(Math.random() * 256)),
  crypto.randomBytes(Math.round(Math.random() * 256)),
];

const port = Math.round(10000 + 10000 * Math.random());
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
const stream = udpToReadableStream(port, '127.0.0.1', { type: 'udp4', reuseAddr: true });

stream.on('data', (chunk) => {
  console.log(`Chunk with length ${chunk.length}`);
});

stream.on('error', (error) => {
  console.error(error);
});

stream.on('close', () => {
  console.log("Close");
});

for (const chunk of chunks) {
  socket.send(chunk, 0, chunk.length, port, '127.0.0.1');
}

stream.destroy(); // Destroying the stream closes the socket
socket.close();

Install

yarn add udp-to-readable-stream

API

Table of Contents

index

Listen to a UDP port and send data to a readable stream.

Parameters

Returns any Readable<Buffer | string>