Avro-js JavaScript Implementation

1.12.1 · active · verified Tue Apr 21

avro-js is a pure JavaScript implementation of the Apache Avro specification, providing efficient data serialization and deserialization. It is currently stable at version 1.12.1, with the Apache Avro project demonstrating an active release cadence, including regular minor and patch updates across its language SDKs. Key differentiators include its reported speed (often twice as fast as JSON with significantly smaller encodings), comprehensive Avro feature support (including recursive schemas, sort order, and schema evolution), and the ability to serialize arbitrary JavaScript objects through logical types. Notably, it boasts zero runtime dependencies and is designed to run both in Node.js environments and modern web browsers. While the core project evolves the Avro specification and multi-language SDKs, avro-js focuses solely on the JavaScript ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic Avro schema parsing, object serialization to a buffer, deserialization back to an object, random instance generation, and schema validation.

import * as avro from 'avro-js';

// 1. Define an Avro schema for a 'Pet' record
const petType = avro.parse({
  name: 'Pet',
  type: 'record',
  fields: [
    {name: 'kind', type: {name: 'Kind', type: 'enum', symbols: ['CAT', 'DOG', 'FISH']}},
    {name: 'name', type: 'string'},
    {name: 'age', type: 'int', default: 0}
  ]
});

// 2. Create a JavaScript object conforming to the schema
const myPet = {kind: 'CAT', name: 'Albert', age: 5};

// 3. Serialize the object to an Avro binary buffer
const buffer = petType.toBuffer(myPet);
console.log('Serialized Buffer:', buffer.toString('hex'));

// 4. Deserialize the buffer back into a JavaScript object
const deserializedPet = petType.fromBuffer(buffer);
console.log('Deserialized Object:', deserializedPet);

// 5. Generate a random instance of the schema
const randomIdType = avro.parse('{"type": "fixed", "name": "Id", "size": 4}');
const randomId = randomIdType.random();
console.log('Random ID (Buffer):', randomId.toString('hex'));

// 6. Check if an object is valid against a schema
const isValid = petType.isValid({kind: 'DOG', name: 'Buddy'});
console.log('Is valid pet object:', isValid);

const isInvalid = petType.isValid({kind: 'FISH', unknownField: 'extra'});
console.log('Is invalid pet object (extra field):', isInvalid);

view raw JSON →