--- /dev/null
+import type { RawData } from 'ws'
+
+/**
+ * Converts WebSocket RawData to string safely
+ * @param message - The RawData from WebSocket
+ * @returns String representation of the message
+ */
+export function rawDataToString (message: RawData): string {
+ if (message instanceof Buffer) {
+ return message.toString()
+ }
+ if (Array.isArray(message)) {
+ return Buffer.concat(message).toString()
+ }
+ return new TextDecoder().decode(message as ArrayBuffer)
+}
type WorkerData,
type WorkerResponse,
} from './types.js'
+import { rawDataToString } from './utils.js'
class WebSocketServerWorker extends ClusterWorker<WorkerData, WorkerResponse> {
private static wss: WebSocketServer
ws.on('error', console.error)
ws.on('message', (message: RawData) => {
const { data, type } = JSON.parse(
- message.toString()
+ rawDataToString(message)
) as MessagePayload<DataPayload>
switch (type) {
case MessageType.echo:
--- /dev/null
+import type { RawData } from 'ws'
+
+/**
+ * Converts WebSocket RawData to string safely
+ * @param message - The RawData from WebSocket
+ * @returns String representation of the message
+ */
+export function rawDataToString (message: RawData): string {
+ if (message instanceof Buffer) {
+ return message.toString()
+ }
+ if (Array.isArray(message)) {
+ return Buffer.concat(message).toString()
+ }
+ return new TextDecoder().decode(message as ArrayBuffer)
+}
type ThreadWorkerData,
type ThreadWorkerResponse,
} from './types.js'
+import { rawDataToString } from './utils.js'
const emptyFunction = (): void => {
/* Intentional */
ws.on('error', console.error)
ws.on('message', (message: RawData) => {
const { data, type } = JSON.parse(
- message.toString()
+ rawDataToString(message)
) as MessagePayload<DataPayload>
switch (type) {
case MessageType.echo:
import { requestHandlerPool } from './pool.js'
import { type DataPayload, type MessagePayload, MessageType } from './types.js'
+import { rawDataToString } from './utils.js'
const port = 8080
const wss = new WebSocketServer({ port }, () => {
ws.on('error', console.error)
ws.on('message', (message: RawData) => {
const { data, type } = JSON.parse(
- message.toString()
+ rawDataToString(message)
) as MessagePayload<DataPayload>
switch (type) {
case MessageType.echo:
--- /dev/null
+import type { RawData } from 'ws'
+
+/**
+ * Converts WebSocket RawData to string safely
+ * @param message - The RawData from WebSocket
+ * @returns String representation of the message
+ */
+export function rawDataToString (message: RawData): string {
+ if (message instanceof Buffer) {
+ return message.toString()
+ }
+ if (Array.isArray(message)) {
+ return Buffer.concat(message).toString()
+ }
+ return new TextDecoder().decode(message as ArrayBuffer)
+}
private writeIdx: number
/**
+ * CircularBuffer constructor.
* @param size - Buffer size.
* @defaultValue defaultBufferSize
* @returns CircularBuffer.