msgpack-lite
msgpack-lite is a pure JavaScript implementation of the MessagePack serialization format, providing fast encoding and decoding capabilities for both Node.js and web browsers. As of version 0.1.26, it offers synchronous `encode` and `decode` functions, along with streaming interfaces via `createEncodeStream` and `createDecodeStream`. It differentiated itself by claiming performance superior to some C++ MessagePack libraries for Node.js v4, without requiring native C++ compilation (node-gyp). The library supports various input types for decoding, including Node.js `Buffer`, standard JavaScript `Array`, and `Uint8Array`. It was tested on older Node.js versions (v0.10 through v6) and a wide range of browsers, including IE8. The last release was over 8 years ago, indicating it is no longer actively maintained.
Common errors
-
TypeError: msgpack.encode is not a function
cause This typically occurs when trying to destructure the `msgpack` object incorrectly or when using `import { encode } from 'msgpack-lite';` in an unsupported environment.fixEnsure you are using `const msgpack = require('msgpack-lite');` and then calling `msgpack.encode()` or `msgpack.decode()`. The module does not provide named exports for ES Modules. -
TypeError: data must be a Buffer or an Array or a Uint8Array
cause The `decode` function received an argument that is not a valid binary type (Node.js Buffer, standard JavaScript Array of numbers, or Uint8Array).fixEnsure the input to `msgpack.decode()` is a `Buffer` (in Node.js), a `Uint8Array`, or a simple `Array` containing byte values (e.g., `[0x81, 0xA3, ...]`). Do not pass raw strings or other object types. -
Error: read after end
cause This error can occur when trying to read from a stream that has already ended or when stream piping/handling is incorrectly set up, leading to attempts to process data from a closed stream.fixVerify that your stream pipeline is correctly configured. Ensure `encodeStream.end()` is called only once all data is written and that subsequent operations respect the stream's state. For reading, ensure `pipe()` is set up before data is expected, and handle `end` events to signal completion.
Warnings
- breaking The `msgpack-lite` package is no longer actively maintained, with its last publish occurring over 8 years ago. This means there will be no updates for new features, bug fixes, or critical security vulnerabilities. Users should consider migrating to actively maintained MessagePack libraries like `@msgpack/msgpack` or `msgpackr` for modern applications.
- gotcha This library is designed for CommonJS (`require`) environments and does not natively support ES Modules (`import`). Using `import` syntax directly in a Node.js ESM context or without proper bundler configuration for browsers will result in module resolution errors.
- gotcha The library primarily deals with Node.js `Buffer` objects for binary data. While it accepts `Uint8Array` for decoding, its core operations in Node.js often produce and expect `Buffer` instances. In modern Node.js, `new Buffer()` is deprecated in favor of `Buffer.from()`, `Buffer.alloc()`, or `Buffer.allocUnsafe()`. Older code examples or existing data might use `new Buffer()`, which could lead to runtime warnings or security issues if not updated.
- gotcha Due to its age and lack of maintenance, `msgpack-lite`'s performance claims (being faster than C++ based `msgpack` on Node.js v4) are likely outdated. Modern MessagePack implementations and V8 engine optimizations have significantly advanced.
Install
-
npm install msgpack-lite -
yarn add msgpack-lite -
pnpm add msgpack-lite
Imports
- msgpack
import msgpack from 'msgpack-lite';
const msgpack = require('msgpack-lite'); - encode, decode
import { encode, decode } from 'msgpack-lite';const { encode, decode } = require('msgpack-lite'); // Not recommended for direct destructuring // Or, preferably: const msgpack = require('msgpack-lite'); const encoded = msgpack.encode(data); - createEncodeStream, createDecodeStream
import { createEncodeStream } from 'msgpack-lite';const msgpack = require('msgpack-lite'); const encodeStream = msgpack.createEncodeStream();
Quickstart
const fs = require('fs');
const msgpack = require('msgpack-lite');
// Example 1: Basic synchronous encoding and decoding
const dataToSend = { id: 1, message: 'Hello, MessagePack!', timestamp: Date.now() };
const buffer = msgpack.encode(dataToSend);
console.log('Encoded buffer:', buffer.toString('hex'));
const decodedData = msgpack.decode(buffer);
console.log('Decoded data:', decodedData);
// Example 2: Streaming encoding and decoding
// Prepare a dummy file path for demonstration
const filePath = 'temp_data.msp';
const writeStream = fs.createWriteStream(filePath);
const encodeStream = msgpack.createEncodeStream();
encodeStream.pipe(writeStream);
encodeStream.write({ event: 'start', time: Date.now() });
encodeStream.write({ user: 'Alice', action: 'login' });
encodeStream.write({ user: 'Bob', action: 'logout' });
// Ensure stream closes after all data is written
encodeStream.end(() => {
console.log(`
Successfully wrote MessagePack data to ${filePath}`);
// Now read from the stream
const readStream = fs.createReadStream(filePath);
const decodeStream = msgpack.createDecodeStream();
console.log('Decoding stream data:');
readStream.pipe(decodeStream).on('data', (obj) => {
console.log('Stream decoded object:', obj);
});
decodeStream.on('end', () => {
console.log('Finished decoding stream.');
fs.unlinkSync(filePath); // Clean up the dummy file
});
decodeStream.on('error', (err) => {
console.error('Error decoding stream:', err);
fs.unlinkSync(filePath); // Clean up on error
});
});
writeStream.on('error', (err) => {
console.error('Error writing to stream:', err);
fs.unlinkSync(filePath); // Clean up on error
});