Skip to content

⚡️ Powerful, high-performance binary compression for Node.js / HTML5

License

Notifications You must be signed in to change notification settings

reececomo/tinybuf

Repository files navigation

🔌 tinybuf  NPM version Minzipped Downloads Tests License

tinybuf icon showing binary peeking out from behind a square.

⚡Fast, compressed binary serializers in Node.js and HTML5

🔮 Simple, declarative API 🔥 Blazing fast serialization
🍃 Zero dependencies 🙉 Strong, inferred types
🗜️ Powerful & performant compression 💾 50% smaller vs FlatBuffers
🌐 Node / browser 🛡️ Built-in validation / transforms
🤏 ~5kb minzipped ✅ Property mangling (Terser)

💿 Install

npm install tinybuf

🕹 Example

import { defineFormat, Type } from 'tinybuf';

export const GameWorldData = defineFormat({
  world: {
    seqNo: Type.UInt,
    time: Type.Float16
  },
  players: [
    {
      id: Type.UInt,
      position: {
        x: Type.Float32,
        y: Type.Float32
      },
      input: {
        move: Type.Scalar,
        buttons: Type.Bools // [ jump, crouch ]
      }
    }
  ]
});

Encode

const bytes = GameWorldData.encode({ /*…*/ });

bytes.byteLength
// 17

Warning

Safe mode: encode(…) optimizes performance and memory by encoding bytes into a shared buffer, and returning a Uint8Array pointer. Subsequent calls are destructive and unsuitable for asyncronous workflows (e.g. Promises, Web Workers).

Enable safe encode to automatically copy bytes to a safe buffer instead:

  • myFormat.encode({ /*…*/ }, true )
  • setTinybufConfig({ safe: true })

Decode

import { bufferParser } from 'tinybuf'

// register formats
const parser = bufferParser()
  .on(GameWorldData, (data) => myWorld.update(data))
  .on(MyChatMessage, (chat) => myHud.showChat(chat));

// process data
parser.processBuffer(bytes)

Or individual:

const data = GameWorldData.decode(bytes);

📘 Documentation

🏁 Quick start
🤔 Types table
📑 Custom headers
🗜️ Compression tips
Validation & transforms

Credits

tinybuf is based on Guilherme Souza's js-binary