LoginSignup
0
3

More than 3 years have passed since last update.

JavaScriptでProtocol Buffersを使う (google-protobuf)

Last updated at Posted at 2020-08-15

画面(JavaScript)からProtocol Buffersを使う機会があったので、メモしておきます。
公式に記載の方法で実施していきます。
https://developers.google.com/protocol-buffers/docs/reference/javascript-generated

必要なもの

demo

※ サンプルコード全量
https://github.com/Thirosue/protocol-buffers-javascript-sample/tree/master/generated-code

インターフェイス定義

インターフェース定義は公式のサンプルを利用します。

person.proto
syntax = "proto3";
package person;

message Person {
  string name = 1;
  uint32 id = 2;
  string email = 3;
}

事前準備

プロジェクト作成

既に作成済みの場合は、スキップしてください。

$ yarn init
yarn init v1.22.4
question name (generated-code):
question version (1.0.0):
question description:
question entry point (index.js):
node_modules/
question repository url:
question author:
question license (MIT):
question private:
success Saved package.json
✨  Done in 3.38s.

モジュールバンドラ(Browserify)インストール

既に導入済みの場合は、スキップしてください。

yarn add --dev browserify

ライブラリインストール

yarn add google-protobuf

クライアントコード生成

## インターフェース定義ファイル(person.proto)がある場所に移動
$ cd /path/to/directory
$ pwd
$ /path/to/directory/protocol-buffers-javascript-sample/generated-code
## クライアントコード生成
$ protoc --proto_path=. --js_out=import_style=commonjs,binary:. person.proto

サンプルコード

index.js
// インターフェース定義を取得する
const person = require('./person_pb');

// インスタンス生成 && 値をセット
const origin = new person.Person();
origin.setName('john doe');
origin.setId(99);
origin.setEmail('test@example.com');

// メッセージを Uint8Array に変換する
const buffer = origin.serializeBinary();
console.log(new TextDecoder().decode(buffer)); // 文字列に変換する

// メッセージをデコードする
const decode = person.Person.deserializeBinary(buffer);
console.log(decode);

// メッセージをオブジェクトに変換する
const obj = origin.toObject();
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3