Skip to content
Daniel Wirtz edited this page Dec 28, 2013 · 101 revisions

ProtoBuf.js is a Protocol Buffers implementation on top of ByteBuffer.js including a .proto parser, reflection, message class building and simple encoding and decoding in plain JavaScript. There is no compilation step required, it's super easy to use and it works out of the box on .proto files.

FAQ:

Usage

node.js / CommonJS

npm install protobufjs
var ProtoBuf = require("protobufjs");
...

RequireJS / AMD

Requires ByteBuffer.js. Optionally depends on Long.js for long (int64) support. If you do not require long support, you can skip the Long.js config. Require.js example:

require.config({
    ...
    "paths": {
        "Long": "/path/to/Long.js",
        "ByteBuffer": "/path/to/ByteBuffer.js",
        "ProtoBuf": "/path/to/ProtoBuf.js"
    },
    ...
});
require(["ProtoBuf"], function(ProtoBuf) {
    ...
});

Or as a module dependency:

define("MyModule", ["ProtoBuf"], function(ProtoBuf) {
    ...
});

Browser

Requires ByteBuffer.js. Optionally depends on Long.js for long (int64) support. If you do not require long support, you can skip the Long.js include.

<script src="Long.min.js"></script>
<script src="ByteBuffer.min.js"></script>
<script src="ProtoBuf.min.js"></script>
var ProtoBuf = dcodeIO.ProtoBuf;
...

Now, everything is set up and ready to go.

Loading .proto files

You'll need the full build to load .proto files and you may either load them from a file or as a string.

// Loading from a file, assuming imports to be relative to that file
// i.e. `import "file2.proto"` will import `path/to/file2.proto`)
var builder = ProtoBuf.loadProtoFile("path/to/file.proto");

// Loading from a file, overriding the import root directory for relative imports
// i.e. `import "to/file2.proto"` will import `./path/to/file2.proto`
var builder = ProtoBuf.loadProtoFile({ root: "./path", file: "to/file.proto" });

// Loading from a string
var builder = ProtoBuf.loadProto(protoString[, filename]);
// The optional filename parameter is required only if imports are used and is
// equivalent to the usage of ProtoBuf.loadProtoFile

Loading .json files created manually or through proto2js is also possible.

Next: Learn more about using the API

Clone this wiki locally