Protocol Buffers are a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more, originally designed at Google (see).
protobuf.js is a pure JavaScript implementation with TypeScript support for Node.js and the browser. It's easy to use, does not sacrifice on performance, has good conformance and works out of the box with .proto files!
Installation<br /> How to include protobuf.js in your project.
Usage<br /> A brief introduction to using the toolset.
Examples<br /> A few examples to get you started.
Additional documentation<br /> A list of available documentation resources.
Performance<br /> A few internals and a benchmark on performance.
Compatibility<br /> Notes on compatibility regarding browsers and optional libraries.
Building<br /> How to build the library and its components yourself.
npm install protobufjs --save
// Static code + Reflection + .proto parser var protobuf = require("protobufjs"); // Static code + Reflection var protobuf = require("protobufjs/light"); // Static code only var protobuf = require("protobufjs/minimal");
The optional command line utility to generate static code and reflection bundles lives in the protobufjs-cli package and can be installed separately:
npm install protobufjs-cli --save-dev
Pick the variant matching your needs and replace the version tag with the exact release your project depends upon. For example, to use the minified full variant:
<script src="//cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.min.js"></script>
| Distribution | Location |
|---|---|
| Full | https://cdn.jsdelivr.net/npm/protobufjs/dist/ |
| Light | https://cdn.jsdelivr.net/npm/protobufjs/dist/light/ |
| Minimal | https://cdn.jsdelivr.net/npm/protobufjs/dist/minimal/ |
All variants support CommonJS and AMD loaders and export globally as window.protobuf.
Because JavaScript is a dynamically typed language, protobuf.js utilizes the concept of a valid message in order to provide the best possible performance (and, as a side product, proper typings):
A valid message is an object (1) not missing any required fields and (2) exclusively composed of JS types understood by the wire format writer.
There are two possible types of valid messages and the encoder is able to work with both of these for convenience:
In a nutshell, the wire format writer understands the following types:
| Field type | Expected JS type (create, encode) | Conversion (fromObject) |
|---|---|---|
| s-/u-/int32<br />s-/fixed32 | number (32 bit integer) | <code>value | 0</code> if signed<br />value >>> 0 if unsigned |
| s-/u-/int64<br />s-/fixed64 | Long-like (optimal)<br />number (53 bit integer) | Long.fromValue(value) with long.js<br />parseInt(value, 10) otherwise |
| float<br />double | number | Number(value) |
| bool | boolean | Boolean(value) |
| string | string | String(value) |
| bytes | Uint8Array (optimal)<br />Buffer (optimal under node)<br />Array.<number> (8 bit integers) | base64.decode(value) if a string<br />Object with non-zero .length is assumed to be buffer-like |
| enum | number (32 bit integer) | Looks up the numeric id if a string |
| message | Valid message | Message.fromObject(value) |
| repeated T | Array<T> | Copy |
| map<K, V> | Object<K,V> | Copy |
undefined and null are considered as not set if the field is optional.Long-likes.With that in mind and again for performance reasons, each message class provides a distinct set of methods with each method doing just one thing. This avoids unnecessary assertions / redundant operations where performance is a concern but also forces a user to perform verification (of plain JavaScript objects that might just so happen to be a valid message) explicitly where necessary - for example when dealing with user input.
Note that Message below refers to any message class.
Message.verify(message: Object): null|string<br />
verifies that a plain JavaScript object satisfies the requirements of a valid message and thus can be encoded without issues. Instead of throwing, it returns the error message as a string, if any.
var payload = "invalid (not an object)"; var err = AwesomeMessage.verify(payload); if (err) throw Error(err);
Message.encode(message: Message|Object [, writer: Writer]): Writer<br />
encodes a message instance or valid plain JavaScript object. This method does not implicitly verify the message and it's up to the user to make sure that the payload is a valid message.
var buffer = AwesomeMessage.encode(message).finish();
Message.encodeDelimited(message: Message|Object [, writer: Writer]): Writer<br />
works like Message.encode but additionally prepends the length of the message as a varint.
Message.decode(reader: Reader|Uint8Array): Message<br />
decodes a buffer to a message instance. If required fields are missing, it throws a util.ProtocolError with an instance property set to the so far decoded message. If the wire format is invalid, it throws an Error.
try { var decodedMessage = AwesomeMessage.decode(buffer); } catch (e) { if (e instanceof protobuf.util.ProtocolError) { // e.instance holds the so far decoded message with missing required fields } else { // wire format is invalid } }
Message.decodeDelimited(reader: Reader|Uint8Array): Message<br />
works like Message.decode but additionally reads the length of the message prepended as a varint.
Message.create(properties: Object): Message<br />
creates a new message instance from a set of properties that satisfy the requirements of a valid message. Where applicable, it is recommended to prefer Message.create over Message.fromObject because it doesn't perform possibly redundant conversion.
var message = AwesomeMessage.create({ awesomeField: "AwesomeString" });
Message.fromObject(object: Object): Message<br />
converts any non-valid plain JavaScript object to a message instance using the conversion steps outlined within the table above.
var message = AwesomeMessage.fromObject({ awesomeField: 42 }); // converts awesomeField to a string
Message.toObject(message: Message [, options: ConversionOptions]): Object<br />
converts a message instance to an arbitrary plain JavaScript object for interoperability with other libraries or storage. The resulting plain JavaScript object might still satisfy the requirements of a valid message depending on the actual conversion options specified, but most of the time it does not.
var object = AwesomeMessage.toObject(message, { enums: String, // enums as string names longs: String, // longs as strings (requires long.js) bytes: String, // bytes as base64 encoded strings defaults: true, // includes default values arrays: true, // populates empty arrays (repeated fields) even if defaults=false objects: true, // populates empty objects (map fields) even if defaults=false oneofs: true // includes virtual oneof fields set to the present field's name });
For reference, the following diagram aims to display relationships between the different methods and the concept of a valid message:
<p align="center"><img alt="Toolset Diagram" src="https://protobufjs.github.io/protobuf.js/toolset.svg" /></p>In other words:
verifyindicates that callingcreateorencodedirectly on the plain object will [result in a valid message respectively] succeed.fromObject, on the other hand, does conversion from a broader range of plain objects to create valid messages. (ref)
It is possible to load existing .proto files using the full library, which parses and compiles the definitions to ready to use (reflection-based) message classes:
// awesome.proto package awesomepackage; syntax = "proto3"; message AwesomeMessage { string awesome_field = 1; // becomes awesomeField }
protobuf.load("awesome.proto", function(err, root) { if (err) throw err; // Obtain a message type var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); // Exemplary payload var payload = { awesomeField: "AwesomeString" }; // Verify the payload if necessary (i.e. when possibly incomplete or invalid) var errMsg = AwesomeMessage.verify(payload); if (errMsg) throw Error(errMsg); // Create a new message var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary // Encode a message to an Uint8Array (browser) or Buffer (node) var buffer = AwesomeMessage.encode(message).finish(); // ... do something with buffer // Decode an Uint8Array (browser) or Buffer (node) to a message var message = AwesomeMessage.decode(buffer); // ... do something with message // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited. // Maybe convert the message back to a plain object var object = AwesomeMessage.toObject(message, { longs: String, enums: String, bytes: String, // see ConversionOptions }); });
Additionally, promise syntax can be used by omitting the callback, if preferred:
protobuf.load("awesome.proto") .then(function(root) { ... });
The library utilizes JSON descriptors that are equivalent to a .proto definition. For example, the following is identical to the .proto definition seen above:
// awesome.json { "nested": { "awesomepackage": { "nested": { "AwesomeMessage": { "fields": { "awesomeField": { "type": "string", "id": 1 } } } } } } }
JSON descriptors closely resemble the internal reflection structure:
| Type (T) | Extends | Type-specific properties |
|---|---|---|
| ReflectionObject | options | |
| Namespace | ReflectionObject | nested |
| Root | Namespace | nested |
| Type | Namespace | fields |
| Enum | ReflectionObject | values |
| Field | ReflectionObject | rule, type, id |
| MapField | Field | keyType |
| OneOf | ReflectionObject | oneof (array of field names) |
| Service | Namespace | methods |
| Method | ReflectionObject | type, requestType, responseType, requestStream, responseStream |
T.fromJSON(name, json) creates the respective reflection object from a JSON descriptorT#toJSON() creates a JSON descriptor from the respective reflection object (its name is used as the key within the parent)Exclusively using JSON descriptors instead of .proto files enables the use of just the light library (the parser isn't required in this case).
A JSON descriptor can either be loaded the usual way:
protobuf.load("awesome.json", function(err, root) { if (err) throw err; // Continue at "Obtain a message type" above });
Or it can be loaded inline:
var jsonDescriptor = require("./awesome.json"); // exemplary for node var root = protobuf.Root.fromJSON(jsonDescriptor); // Continue at "Obtain a message type" above
Both the full and the light library include full reflection support. One could, for example, define the .proto definitions seen in the examples above using just reflection:
... var Root = protobuf.Root, Type = protobuf.Type, Field = protobuf.Field; var AwesomeMessage = new Type("AwesomeMessage").add(new Field("awesomeField", 1, "string")); var root = new Root().define("awesomepackage").add(AwesomeMessage); // Continue at "Create a new message" above ...
Detailed information on the reflection structure is available within the API documentation.
Message classes can also be extended with custom functionality and it is also possible to register a custom constructor with a reflected message type:
... // Define a custom constructor function AwesomeMessage(properties) { // custom initialization code ... } // Register the custom constructor with its reflected type (*) root.lookupType("awesomepackage.AwesomeMessage").ctor = AwesomeMessage; // Define custom functionality AwesomeMessage.customStaticMethod = function() { ... }; AwesomeMessage.prototype.customInstanceMethod = function() { ... }; // Continue at "Create a new message" above
(*) Besides referencing its reflected type through AwesomeMessage.$type and AwesomeMesage#$type, the respective custom class is automatically populated with:
AwesomeMessage.createAwesomeMessage.encode and AwesomeMessage.encodeDelimitedAwesomeMessage.decode and AwesomeMessage.decodeDelimitedAwesomeMessage.verifyAwesomeMessage.fromObject, AwesomeMessage.toObject and AwesomeMessage#toJSONAfterwards, decoded messages of this type are instanceof AwesomeMessage.
Alternatively, it is also possible to reuse and extend the internal constructor if custom initialization code is not required:
... // Reuse the internal constructor var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage").ctor; // Define custom functionality AwesomeMessage.customStaticMethod = function() { ... }; AwesomeMessage.prototype.customInstanceMethod = function() { ... }; // Continue at "Create a new message" above
The library also supports consuming services but it doesn't make any assumptions about the actual transport channel. Instead, a user must provide a suitable RPC implementation, which is an asynchronous function that takes the reflected service method, the binary request and a node-style callback as its parameters:
function rpcImpl(method, requestData, callback) { // perform the request using an HTTP request or a WebSocket for example var responseData = ...; // and call the callback with the binary response afterwards: callback(null, responseData); }
Below is a working example with a typescript implementation using grpc npm package.
const grpc = require('grpc') const Client = grpc.makeGenericClientConstructor({}) const client = new Client( grpcServerUrl, grpc.credentials.createInsecure() ) const rpcImpl = function(method, requestData, callback) { client.makeUnaryRequest( method.name, arg => arg, arg => arg, requestData, callback ) }
Example:
//


职场AI,就用扣子
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!


多风格AI绘画神器
堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。


零代码AI应用开发平台
零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。


免费创建高清无水印Sora视 频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图 效率,让品牌能够快速上架。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号