MessagePack for ECMA-262/JavaScript/TypeScript
This library is an implementation of MessagePack for TypeScript and JavaScript, providing a compact and efficient binary serialization format. Learn more about MessagePack at:
https://msgpack.org/
This library serves as a comprehensive reference implementation of MessagePack for JavaScript with a focus on accuracy, compatibility, interoperability, and performance.
Additionally, this is also a universal JavaScript library. It is compatible not only with browsers, but with Node.js or other JavaScript engines that implement ES2015+ standards. As it is written in TypeScript, this library bundles up-to-date type definition files (d.ts).
*Note that this is the second edition of "MessagePack for JavaScript". The first edition, which was implemented in ES5 and never released to npmjs.com, is tagged as classic.
Synopsis
import { deepStrictEqual } from "assert";
import { encode, decode } from "@msgpack/msgpack";
const object = {
nil: null,
integer: 1,
float: Math.PI,
string: "Hello, world!",
binary: Uint8Array.from([1, 2, 3]),
array: [10, 20, 30],
map: { foo: "bar" },
timestampExt: new Date(),
};
const encoded: Uint8Array = encode(object);
deepStrictEqual(decode(encoded), object);
Table of Contents
Install
This library is published to npmjs.com as @msgpack/msgpack.
npm install @msgpack/msgpack
API
encode(data: unknown, options?: EncoderOptions): Uint8Array
It encodes data into a single MessagePack-encoded object, and returns a byte array as Uint8Array. It throws errors if data is, or includes, a non-serializable object such as a function or a symbol.
for example:
import { encode } from "@msgpack/msgpack";
const encoded: Uint8Array = encode({ foo: "bar" });
console.log(encoded);
If you'd like to convert an uint8array to a NodeJS Buffer, use Buffer.from(arrayBuffer, offset, length) in order not to copy the underlying ArrayBuffer, while Buffer.from(uint8array) copies it:
import { encode } from "@msgpack/msgpack";
const encoded: Uint8Array = encode({ foo: "bar" });
// `buffer` refers the same ArrayBuffer as `encoded`.
const buffer: Buffer = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
console.log(buffer);
EncoderOptions
| Name |
Type |
Default |
| extensionCodec |
ExtensionCodec |
ExtensionCodec.defaultCodec |
| context |
user-defined |
- |
| useBigInt64 |
boolean |
false |
| maxDepth |
number |
100 |
| initialBufferSize |
number |
2048 |
| sortKeys |
boolean |
false |
| forceFloat32 |
boolean |
false |
| forceIntegerToFloat |
boolean |
false |
| ignoreUndefined |
boolean |
false |
decode(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): unknown
It decodes buffer that includes a MessagePack-encoded object, and returns the decoded object typed unknown.
buffer must be an array of bytes, which is typically Uint8Array or ArrayBuffer. BufferSource is defined as ArrayBuffer | ArrayBufferView.
The buffer must include a single encoded object. If the buffer includes extra bytes after an object or the buffer is empty, it throws RangeError. To decode buffer that includes multiple encoded objects, use decodeMulti() or decodeMultiStream() (recommended) instead.
for example:
import { decode } from "@msgpack/msgpack";
const encoded: Uint8Array;
const object = decode(encoded);
console.log(object);
NodeJS Buffer is also acceptable because it is a subclass of Uint8Array.
DecoderOptions
| Name |
Type |
Default |
| extensionCodec |
ExtensionCodec |
ExtensionCodec.defaultCodec |
| context |
user-defined |
- |
| useBigInt64 |
boolean |
false |
| rawStrings |
boolean |
false |
| maxStrLength |
number |
4_294_967_295 (UINT32_MAX) |
| maxBinLength |
number |
4_294_967_295 (UINT32_MAX) |
| maxArrayLength |
number |
4_294_967_295 (UINT32_MAX) |
| maxMapLength |
number |
4_294_967_295 (UINT32_MAX) |
| maxExtLength |
number |
4_294_967_295 (UINT32_MAX) |
| mapKeyConverter |
MapKeyConverterType |
throw exception if key is not string or number |
MapKeyConverterType is defined as (key: unknown) => string | number.
To skip UTF-8 decoding of strings, rawStrings can be set to true. In this case, strings are decoded into Uint8Array.
You can use max${Type}Length to limit the length of each type decoded.
decodeMulti(buffer: ArrayLike<number> | BufferSource, options?: DecoderOptions): Generator<unknown, void, unknown>
It decodes buffer that includes multiple MessagePack-encoded objects, and returns decoded objects as a generator. See also decodeMultiStream(), which is an asynchronous variant of this function.
This function is not recommended to decode a MessagePack binary via I/O stream including sockets because it's synchronous. Instead, decodeMultiStream() decodes a binary stream asynchronously, typically spending less CPU and memory.
for example:
import { decode } from "@msgpack/msgpack";
const encoded: Uint8Array;
for (const object of decodeMulti(encoded)) {
console.log(object);
}
decodeAsync(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): Promise<unknown>
It decodes stream, where ReadableStreamLike<T> is defined as ReadableStream<T> | AsyncIterable<T>, in an async iterable of byte arrays, and returns decoded object as unknown type, wrapped in Promise.
This function works asynchronously, and might CPU resources more efficiently compared with synchronous decode(), because it doesn't wait for the completion of downloading.
This function is designed to work with whatwg fetch() like this:
import { decodeAsync } from "@msgpack/msgpack";
const MSGPACK_TYPE = "application/x-msgpack";
const response = await fetch(url);
const contentType = response.headers.get("Content-Type");
if (contentType && contentType.startsWith(MSGPACK_TYPE) && response.body != null) {
const object = await decodeAsync(response.body);
// do something with object
} else { /* handle errors */ }
decodeArrayStream(stream: ReadableStreamLike<ArrayLike<number> | BufferSource>, options?: DecoderOptions): AsyncIterable<unknown>
It is alike to decodeAsync()