protobufjs / protobuf.js

Protocol Buffers for JavaScript & TypeScript.
Other
9.92k stars 1.41k forks source link

A newbie tutorial please? #1561

Open frederikhors opened 3 years ago

frederikhors commented 3 years ago

I'm new to Protocol buffers and gRPC.

I'm following the "Code Generator Plugin" and "Client Configuration Options" guides and the amazing Percy Bolmer's tutorial.

They say to use this command to generate .js files:

$ protoc -I=$DIR echo.proto \
    --js_out=import_style=commonjs:$OUT_DIR \
    --grpc-web_out=import_style=commonjs,mode=grpcwebtext:$OUT_DIR

I'm using this .proto file:

syntax = "proto3";

package main;

option go_package = ".;hardwaremonitoring";

message HardwareStats {
  string uptime = 1;
  int32 memory_free = 2;
  int32 memory_used = 3;
}

message EmptyRequest{}

service HardwareMonitor {
  rpc Monitor(EmptyRequest) returns (stream HardwareStats) {};
}

then I'm using the below code in my JS app:

import { HardwareMonitorClient } from "./proto/service_grpc_web_pb";
import { EmptyRequest } from "./proto/service_pb";

const client = new HardwareMonitorClient("http://localhost:3000");

// custom code...

const customFunction = () => {
    var request = new EmptyRequest();

    var stream = client.monitor(request, {});

    stream.on("data", function (response) {
        var stats = response.toObject();
        // custom code...
    });
};

How to use protobuf.js now?

Can I generate my JS code like I do now with protoc-gen-grpc-web?

Am I completely wrong?

alexander-fenster commented 3 years ago

In this example, you don't use protobuf.js, you're using protoc-generated stubs instead. Protobuf.js has nothing to do with protoc and there is no protoc plugin (that I'm aware of) that generates protobuf.js representation.

The official gRPC guide uses protobuf.js (and not protoc) though so you could look there.