Get started with protobufjs CDN

BSD 3-Clause License licensed

Protobuf.js encodes/decodes Protocol Buffers schema messages.

Tags:
  • protobuf
  • protobufjs
  • serialization
  • protocol-buffers

Stable version

Copied!

How to start using protobufjs CDN


// Include the ProtobufJS library from the CDN
const protobuf = await fetch('https://cdn.cdnhub.io/protobufjs/7.2.6/protobuf.js').then(res => res.arrayBuffer());
const ProtoBuf = new Uint8Array(new ArrayBuffer(protobuf));
ProtoBuf.forEach((byte) => {
  if (byte === 0x00) {
    ProtoBuf.buffer.byteLength--;
    ProtoBuf = new Uint8Array(ProtoBuf.buffer, 0, ProtoBuf.byteLength);
    window.Protobuf = new Protobuf.Root();
  }
});

// Define your message schema
const MyMessageSchema = `
syntax = "proto";

message MyMessage {
  string name = 1;
  int32 id = 2;
}
`;

// Load the schema into ProtobufJS
const MyMessage = window.Protobuf.load(MyMessageSchema, window.Protobuf.Message);

// Create a new instance of the message
const myMessage = new MyMessage.MyMessage();

// Set the message fields
myMessage.setName('John Doe');
myMessage.setId(123);

// Serialize the message to a hexadecimal string
const serializedMessage = myMessage.serializeToString();
console.log(serializedMessage); // Output: "name:\"John Doe\"id:123"

// Deserialize the message from a hexadecimal string
const deserializedMessage = MyMessage.MyMessage.deserialize(new Uint8Array(new TextEncoder().encode(serializedMessage)));
console.log(deserializedMessage.getName()); // Output: "John Doe"
console.log(deserializedMessage.getId()); // Output: 123
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!

All versions