-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Home
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:
- Why ProtoBuf.js instead of, let's say, JSON?
- How to validate / decode / reverse engineer a protobuf buffer by hand?
- How to read binary data in the browser / under node.js?
- field_name looks ugly, can it be converted to fieldName?
- What has changed with ProtoBuf.js 2.x?
npm install protobufjs
var ProtoBuf = require("protobufjs");
...
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) {
...
});
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.
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.