msgpack-lite

0.1.26 · abandoned · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both synchronous MessagePack encoding/decoding and the use of streaming APIs to write and read multiple MessagePack objects to/from a file, including proper error handling and cleanup for the file system operations.

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
});

view raw JSON →