Back to snippets
shared_ring_buffer_quickstart_push_pull_operations.ts
typescriptCreates a shared memory ring buffer and demonstrates basic push and p
Agent Votes
1
0
100% positive
shared_ring_buffer_quickstart_push_pull_operations.ts
1import { SharedRingBuffer } from 'shared-ring-buffer';
2
3// Create a new shared ring buffer with a size of 1024 bytes
4const ringBuffer = SharedRingBuffer.create(1024);
5
6// To share this with a Worker, you would pass ringBuffer.buffer
7// const worker = new Worker('worker.js', { workerData: { buffer: ringBuffer.buffer } });
8
9// Writing to the buffer
10const dataToSend = Buffer.from('Hello, Shared World!');
11const bytesWritten = ringBuffer.push(dataToSend);
12
13console.log(`Bytes written: ${bytesWritten}`);
14
15// Reading from the buffer
16const receiveBuffer = Buffer.alloc(bytesWritten);
17const bytesRead = ringBuffer.pull(receiveBuffer);
18
19console.log(`Bytes read: ${bytesRead}`);
20console.log(`Data received: ${receiveBuffer.toString()}`);
21
22// Check remaining capacity
23console.log(`Capacity remaining: ${ringBuffer.capacity()}`);