Avsc - Avro for JavaScript

5.7.9 · active · verified Sun Apr 19

Avsc is a pure JavaScript implementation of the Apache Avro specification, currently stable at version 5.7.9. It provides fast and compact data serialization and deserialization, often outperforming JSON with smaller encodings. Key features include comprehensive support for Avro type inference, schema evolution, logical types (e.g., handling JavaScript Date objects transparently), and remote procedure calls (RPC) with IDL support. The library is actively maintained, with recent minor updates indicating ongoing development. It differentiates itself by offering a complete Avro ecosystem within JavaScript, making it suitable for high-performance data interchange and integration with Avro-based systems like Apache Kafka, especially in Node.js environments. The package also ships with built-in TypeScript type definitions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an Avro schema, create an Avro `Type`, and then use it to encode and decode JavaScript objects into binary buffers. It also shows basic type inference.

import { Type } from 'avsc';

const petSchema = {
  type: 'record',
  name: 'Pet',
  fields: [
    {
      name: 'kind',
      type: { type: 'enum', name: 'PetKind', symbols: ['CAT', 'DOG', 'FISH'] }
    },
    { name: 'name', type: 'string' }
  ]
};

// Create an Avro Type from a schema definition
const petType = Type.forSchema(petSchema);

// Encode a JavaScript object into an Avro binary buffer
const myPet = { kind: 'CAT', name: 'Albert' };
const buf = petType.toBuffer(myPet);

console.log('Original object:', myPet);
console.log('Encoded buffer:', buf.toString('hex'));

// Decode the Avro binary buffer back into a JavaScript object
const decodedPet = petType.fromBuffer(buf);

console.log('Decoded object:', decodedPet);

// Example of schema inference for similar structures
const addressType = Type.forValue({
  city: 'Cambridge',
  zipCodes: ['02138', '02139'],
  visits: 2
});

const otherAddress = { city: 'Seattle', zipCodes: ['98101'], visits: 3 };
const otherBuf = addressType.toBuffer(otherAddress);
console.log('\nInferred schema for:', otherAddress);
console.log('Encoded (inferred) buffer:', otherBuf.toString('hex'));

view raw JSON →