Function serializeToBuffer

Serialize any data to a Buffer, useful when working with web sockets or other binary protocols. Make sure to understand how serialize works before using this function.

To make this function work in browsers it accepts a BufferImplementation parameter. To make the serialization customizable it accepts a serializeArgs parameter. It's therefore recommended to first prepare the function with bind, like:

import { serializeToBuffer as serializeRaw } from "@ezez/utils";
import { Buffer } from "buffer/"; // skip import in Node.js

// prepare the function:
const serializeToBuffer = serializeRaw.bind(null, Buffer, []); // array is customization params for serialize

const serialized = serializeToBuffer("test", 1, { test: "test" });

Otherwise pass the params each time:

import { serializeToBuffer as serializeRaw } from "@ezez/utils";
const serialized = serializeToBuffer(Buffer, [], "test", 1, { test: "test" });
const otherSerialized = serializeToBuffer(Buffer, [], any, other, data);
  • Parameters

    • BufferImplementation: BufferConstructor

      Buffer implementation, in browsers use buffer npm package and import it from buffer/, in Node.js simply pass Buffer.

    • serializeArgs: [customSerializers?: CustomSerializers, options?: Options]

      [customSerializers, options] - optional arguments if you need to serialize custom data types, see: serialize

    • Rest...args: unknown[]

      any data to serialize, can be a Buffer, string or any other data type

    Returns Buffer<ArrayBufferLike>

    Buffer - serialized data